<!DOCTYPE html>












  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <!-- hexo-inject:begin --><!-- hexo-inject:end --><meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">


  
  
  <link rel="stylesheet" href="/xieyuanhui/lib/needsharebutton/needsharebutton.css">

















  
  
  <link rel="stylesheet" href="/xieyuanhui/lib/fancybox/source/jquery.fancybox.css">







<link rel="stylesheet" href="/xieyuanhui/lib/font-awesome/css/font-awesome.min.css?v=4.6.2">

<link rel="stylesheet" href="/xieyuanhui/css/main.css?v=7.1.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/xieyuanhui/images/apple-touch-icon-next.png?v=7.1.0">


  <link rel="icon" type="image/png" sizes="32x32" href="/xieyuanhui/images/favicon-32x32-next.png?v=7.1.0">


  <link rel="icon" type="image/png" sizes="16x16" href="/xieyuanhui/images/favicon-16x16-next.png?v=7.1.0">


  <link rel="mask-icon" href="/xieyuanhui/images/logo.svg?v=7.1.0" color="#222">


  <link rel="manifest" href="/xieyuanhui/images/manifest.json">


  <meta name="msapplication-config" content="/xieyuanhui/images/browserconfig.xml">





<script id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/xieyuanhui/',
    scheme: 'Pisces',
    version: '7.1.0',
    sidebar: {"position":"left","display":"post","offset":12,"onmobile":false,"dimmer":false},
    back2top: true,
    back2top_sidebar: false,
    fancybox: true,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="原文地址：Spring：源码解读Spring IOC原理 一、什么是Ioc/DI？IoC 容器：最主要是完成了完成对象的创建和依赖的管理注入等等。 先从我们自己设计这样一个视角来考虑： 所谓控制反转，就是把原先我们代码里面需要实现的对象创建、依赖的代码，反转给容器来帮忙实现。那么必然的我们需要创建一个容器，同时需要一种描述来让容器知道需要创建的对象与对象的关系。这个描述最具体表现就是我们可配置的文">
<meta name="keywords" content="Spring,IOC">
<meta property="og:type" content="article">
<meta property="og:title" content="Spring IOC源码解析">
<meta property="og:url" content="http://xyh5513.gitee.io/xieyuanhui/2019/06/28/Spring-IOC源码解析/index.html">
<meta property="og:site_name" content="xieyuanhui的笔记">
<meta property="og:description" content="原文地址：Spring：源码解读Spring IOC原理 一、什么是Ioc/DI？IoC 容器：最主要是完成了完成对象的创建和依赖的管理注入等等。 先从我们自己设计这样一个视角来考虑： 所谓控制反转，就是把原先我们代码里面需要实现的对象创建、依赖的代码，反转给容器来帮忙实现。那么必然的我们需要创建一个容器，同时需要一种描述来让容器知道需要创建的对象与对象的关系。这个描述最具体表现就是我们可配置的文">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://xyh5513.gitee.io/xieyuanhui/2019/06/28/Spring-IOC源码解析/img1.jpg">
<meta property="og:image" content="http://xyh5513.gitee.io/xieyuanhui/2019/06/28/Spring-IOC源码解析/img2.jpg">
<meta property="og:image" content="http://xyh5513.gitee.io/xieyuanhui/2019/06/28/Spring-IOC源码解析/img3.jpg">
<meta property="og:image" content="http://xyh5513.gitee.io/xieyuanhui/2019/06/28/Spring-IOC源码解析/img4.jpg">
<meta property="og:image" content="http://xyh5513.gitee.io/xieyuanhui/2019/06/28/Spring-IOC源码解析/img5.jpg">
<meta property="og:image" content="http://xyh5513.gitee.io/xieyuanhui/2019/06/28/Spring-IOC源码解析/img6.jpg">
<meta property="og:updated_time" content="2019-07-08T09:14:30.650Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Spring IOC源码解析">
<meta name="twitter:description" content="原文地址：Spring：源码解读Spring IOC原理 一、什么是Ioc/DI？IoC 容器：最主要是完成了完成对象的创建和依赖的管理注入等等。 先从我们自己设计这样一个视角来考虑： 所谓控制反转，就是把原先我们代码里面需要实现的对象创建、依赖的代码，反转给容器来帮忙实现。那么必然的我们需要创建一个容器，同时需要一种描述来让容器知道需要创建的对象与对象的关系。这个描述最具体表现就是我们可配置的文">
<meta name="twitter:image" content="http://xyh5513.gitee.io/xieyuanhui/2019/06/28/Spring-IOC源码解析/img1.jpg">



  <link rel="alternate" href="/xieyuanhui/atom.xml" title="xieyuanhui的笔记" type="application/atom+xml">



  
  
  <link rel="canonical" href="http://xyh5513.gitee.io/xieyuanhui/2019/06/28/Spring-IOC源码解析/">



<script id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>Spring IOC源码解析 | xieyuanhui的笔记</title>
  












  <noscript>
  <style>
  .use-motion .motion-element,
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-title { opacity: initial; }

  .use-motion .logo,
  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript><!-- hexo-inject:begin --><!-- hexo-inject:end -->

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <!-- hexo-inject:begin --><!-- hexo-inject:end --><div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta">
    

    <div class="custom-logo-site-title">
      <a href="/xieyuanhui/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">xieyuanhui的笔记</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">

    
    
    
      
    

    

    <a href="/xieyuanhui/" rel="section"><i class="menu-item-icon fa fa-fw fa-home"></i> <br>首页</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-about">

    
    
    
      
    

    

    <a href="/xieyuanhui/about/" rel="section"><i class="menu-item-icon fa fa-fw fa-user"></i> <br>关于</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">

    
    
    
      
    

    

    <a href="/xieyuanhui/tags/" rel="section"><i class="menu-item-icon fa fa-fw fa-tags"></i> <br>标签</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">

    
    
    
      
    

    

    <a href="/xieyuanhui/categories/" rel="section"><i class="menu-item-icon fa fa-fw fa-th"></i> <br>分类</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">

    
    
    
      
    

    

    <a href="/xieyuanhui/archives/" rel="section"><i class="menu-item-icon fa fa-fw fa-archive"></i> <br>归档</a>

  </li>

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>搜索</a>
        </li>
      
    </ul>
  

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
            

          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://xyh5513.gitee.io/xieyuanhui/xieyuanhui/2019/06/28/Spring-IOC源码解析/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="xieyuanhui">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/xieyuanhui/images/deer.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="xieyuanhui的笔记">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Spring IOC源码解析

              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2019-06-28 11:29:43" itemprop="dateCreated datePublished" datetime="2019-06-28T11:29:43+08:00">2019-06-28</time>
            

            
              

              
                
                <span class="post-meta-divider">|</span>
                

                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                
                  <span class="post-meta-item-text">更新于</span>
                
                <time title="修改时间：2019-07-08 17:14:30" itemprop="dateModified" datetime="2019-07-08T17:14:30+08:00">2019-07-08</time>
              
            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/xieyuanhui/categories/Spring/" itemprop="url" rel="index"><span itemprop="name">Spring</span></a></span>

                
                
              
            </span>
          

          
            
            
          

          
          
            <span id="/xieyuanhui/2019/06/28/Spring-IOC源码解析/" class="leancloud_visitors" data-flag-title="Spring IOC源码解析">
              <span class="post-meta-divider">|</span>
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              
                <span class="post-meta-item-text">阅读次数：</span>
              
                <span class="leancloud-visitors-count"></span>
            </span>
          

          

          
            <div class="post-symbolscount">
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">本文字数：</span>
                
                <span title="本文字数">49k</span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">45 分钟</span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>原文地址：<a href="https://www.cnblogs.com/ITtangtang/p/3978349.html" target="_blank" rel="noopener">Spring：源码解读Spring IOC原理</a></p>
<h2 id="一、什么是Ioc-DI？"><a href="#一、什么是Ioc-DI？" class="headerlink" title="一、什么是Ioc/DI？"></a>一、什么是Ioc/DI？</h2><p>IoC 容器：最主要是完成了完成对象的创建和依赖的管理注入等等。</p>
<p>先从我们自己设计这样一个视角来考虑：</p>
<p>所谓控制反转，就是把原先我们代码里面需要实现的对象创建、依赖的代码，反转给容器来帮忙实现。那么必然的我们需要创建一个容器，同时需要一种描述来让容器知道需要创建的对象与对象的关系。这个描述最具体表现就是我们可配置的文件。</p>
<p>对象和对象关系怎么表示？</p>
<p>可以用 xml ， properties 文件等语义化配置文件表示。</p>
<p>描述对象关系的文件存放在哪里？</p>
<p>可能是 classpath ， filesystem ，或者是 URL 网络资源， servletContext 等。</p>
<p>回到正题，有了配置文件，还需要对配置文件解析。</p>
<p>不同的配置文件对对象的描述不一样，如标准的，自定义声明式的，如何统一？ 在内部需要有一个统一的关于对象的定义，所有外部的描述都必须转化成统一的描述定义。</p>
<p>如何对不同的配置文件进行解析？需要对不同的配置文件语法，采用不同的解析器</p>
<h2 id="二、-Spring-IOC体系结构？"><a href="#二、-Spring-IOC体系结构？" class="headerlink" title="二、 Spring IOC体系结构？"></a>二、 Spring IOC体系结构？</h2><h3 id="1-BeanFactory"><a href="#1-BeanFactory" class="headerlink" title="(1) BeanFactory"></a>(1) BeanFactory</h3><p>Spring Bean的创建是典型的工厂模式，这一系列的Bean工厂，也即IOC容器为开发者管理对象间的依赖关系提供了很多便利和基础服务，在Spring中有许多的IOC容器的实现供用户选择和使用，其相互关系如下：</p>
<p><img src="/xieyuanhui/2019/06/28/Spring-IOC源码解析/img1.jpg" alt></p>
<p>其中BeanFactory作为最顶层的一个接口类，它定义了IOC容器的基本功能规范，BeanFactory 有三个子类：ListableBeanFactory、HierarchicalBeanFactory 和AutowireCapableBeanFactory。但是从上图中我们可以发现最终的默认实现类是 DefaultListableBeanFactory，他实现了所有的接口。那为何要定义这么多层次的接口呢？查阅这些接口的源码和说明发现，每个接口都有他使用的场合，它主要是为了区分在 Spring 内部在操作过程中对象的传递和转化过程中，对对象的数据访问所做的限制。例如 ListableBeanFactory 接口表示这些 Bean 是可列表的，而 HierarchicalBeanFactory 表示的是这些 Bean 是有继承关系的，也就是每个Bean 有可能有父 Bean。AutowireCapableBeanFactory 接口定义 Bean 的自动装配规则。这四个接口共同定义了 Bean 的集合、Bean 之间的关系、以及 Bean 行为.</p>
<p>最基本的IOC容器接口BeanFactory</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">BeanFactory</span> </span>&#123;</span><br><span class="line">    <span class="comment">//对FactoryBean的转义定义，因为如果使用bean的名字检索FactoryBean得到的对象是工厂生成的对象，如果需要得到工厂本身，需要转义 </span></span><br><span class="line">    String FACTORY_BEAN_PREFIX = <span class="string">"&amp;"</span>;</span><br><span class="line">	<span class="comment">//根据bean的名字，获取在IOC容器中得到bean实例 </span></span><br><span class="line">    <span class="function">Object <span class="title">getBean</span><span class="params">(String var1)</span> <span class="keyword">throws</span> BeansException</span>;</span><br><span class="line">	<span class="comment">//根据bean的名字和Class类型来得到bean实例，增加了类型安全验证机制。    </span></span><br><span class="line">    &lt;T&gt; <span class="function">T <span class="title">getBean</span><span class="params">(String var1, Class&lt;T&gt; var2)</span> <span class="keyword">throws</span> BeansException</span>;</span><br><span class="line"></span><br><span class="line">    <span class="function">Object <span class="title">getBean</span><span class="params">(String var1, Object... var2)</span> <span class="keyword">throws</span> BeansException</span>;</span><br><span class="line"></span><br><span class="line">    &lt;T&gt; <span class="function">T <span class="title">getBean</span><span class="params">(Class&lt;T&gt; var1)</span> <span class="keyword">throws</span> BeansException</span>;</span><br><span class="line"></span><br><span class="line">    &lt;T&gt; <span class="function">T <span class="title">getBean</span><span class="params">(Class&lt;T&gt; var1, Object... var2)</span> <span class="keyword">throws</span> BeansException</span>;</span><br><span class="line"></span><br><span class="line">    &lt;T&gt; <span class="function">ObjectProvider&lt;T&gt; <span class="title">getBeanProvider</span><span class="params">(Class&lt;T&gt; var1)</span></span>;</span><br><span class="line"></span><br><span class="line">    &lt;T&gt; <span class="function">ObjectProvider&lt;T&gt; <span class="title">getBeanProvider</span><span class="params">(ResolvableType var1)</span></span>;</span><br><span class="line">	<span class="comment">//提供对bean的检索，看看是否在IOC容器有这个名字的bean    </span></span><br><span class="line">    <span class="function"><span class="keyword">boolean</span> <span class="title">containsBean</span><span class="params">(String var1)</span></span>;</span><br><span class="line">	<span class="comment">//根据bean名字得到bean实例，并同时判断这个bean是不是单例  </span></span><br><span class="line">    <span class="function"><span class="keyword">boolean</span> <span class="title">isSingleton</span><span class="params">(String var1)</span> <span class="keyword">throws</span> NoSuchBeanDefinitionException</span>;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">boolean</span> <span class="title">isPrototype</span><span class="params">(String var1)</span> <span class="keyword">throws</span> NoSuchBeanDefinitionException</span>;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">boolean</span> <span class="title">isTypeMatch</span><span class="params">(String var1, ResolvableType var2)</span> <span class="keyword">throws</span> NoSuchBeanDefinitionException</span>;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">boolean</span> <span class="title">isTypeMatch</span><span class="params">(String var1, Class&lt;?&gt; var2)</span> <span class="keyword">throws</span> NoSuchBeanDefinitionException</span>;</span><br><span class="line">	<span class="comment">//得到bean实例的Class类型  </span></span><br><span class="line">    <span class="meta">@Nullable</span></span><br><span class="line">    Class&lt;?&gt; getType(String var1) <span class="keyword">throws</span> NoSuchBeanDefinitionException;</span><br><span class="line">	<span class="comment">//得到bean的别名，如果根据别名检索，那么其原名也会被检索出来</span></span><br><span class="line">    String[] getAliases(String var1);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>在BeanFactory里只对IOC容器的基本行为作了定义，根本不关心你的bean是如何定义怎样加载的。正如我们只关心工厂里得到什么的产品对象，至于工厂是怎么生产这些对象的，这个基本的接口不关心。</p>
<p>​            而要知道工厂是如何产生对象的，我们需要看具体的IOC容器实现，spring提供了许多IOC容器的实现。比如XmlBeanFactory，ClasspathXmlApplicationContext等。其中XmlBeanFactory就是针对最基本的ioc容器的实现，这个IOC容器可以读取XML文件定义的BeanDefinition（XML文件中对bean的描述）,如果说XmlBeanFactory是容器中的屌丝，ApplicationContext应该算容器中的高帅富.</p>
<p>​            ApplicationContext是Spring提供的一个高级的IoC容器，它除了能够提供IoC容器的基本功能外，还为用户提供了以下的附加服务。 </p>
<p>从ApplicationContext接口的实现，我们看出其特点：</p>
<ul>
<li>支持信息源，可以实现国际化。（实现MessageSource接口）</li>
<li>访问资源。(实现ResourcePatternResolver接口，这个后面要讲)</li>
<li>支持应用事件。(实现ApplicationEventPublisher接口)</li>
</ul>
<h3 id="2-BeanDefinition"><a href="#2-BeanDefinition" class="headerlink" title="(2) BeanDefinition"></a>(2) BeanDefinition</h3><p>SpringIOC容器管理了我们定义的各种Bean对象及其相互的关系，Bean对象在Spring实现中是以BeanDefinition来描述的，其继承体系如下：</p>
<p><img src="/xieyuanhui/2019/06/28/Spring-IOC源码解析/img2.jpg" alt></p>
<p>Bean 的解析过程非常复杂，功能被分的很细，因为这里需要被扩展的地方很多，必须保证有足够的灵活性，以应对可能的变化。Bean 的解析主要就是对 Spring 配置文件的解析。这个解析过程主要通过下图中的类完成：</p>
<p><img src="/xieyuanhui/2019/06/28/Spring-IOC源码解析/img3.jpg" alt></p>
<h2 id="三、IoC容器的初始化？"><a href="#三、IoC容器的初始化？" class="headerlink" title="三、IoC容器的初始化？"></a>三、IoC容器的初始化？</h2><p>IoC容器的初始化包括BeanDefinition的Resource定位、载入和注册这三个基本的过程。我们以ApplicationContext为例讲解，ApplicationContext系列容器也许是我们最熟悉的，因为web项目中使用的XmlWebApplicationContext就属于这个继承体系，还有ClasspathXmlApplicationContext等，其继承体系如下图所示：</p>
<p><img src="/xieyuanhui/2019/06/28/Spring-IOC源码解析/img4.jpg" alt></p>
<p>ApplicationContext允许上下文嵌套，通过保持父上下文可以维持一个上下文体系。对于bean的查找可以在这个上下文体系中发生，首先检查当前上下文，其次是父上下文，逐级向上，这样为不同的Spring应用提供了一个共享的bean定义环境。</p>
<p>下面我们分别简单地演示一下两种ioc容器的创建过程</p>
<h3 id="1、XmlBeanFactory-屌丝IOC-的整个流程"><a href="#1、XmlBeanFactory-屌丝IOC-的整个流程" class="headerlink" title="1、XmlBeanFactory(屌丝IOC)的整个流程"></a>1、XmlBeanFactory(屌丝IOC)的整个流程</h3><p>通过XmlBeanFactory的源码，我们可以发现:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Deprecated</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">XmlBeanFactory</span> <span class="keyword">extends</span> <span class="title">DefaultListableBeanFactory</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> XmlBeanDefinitionReader reader;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">XmlBeanFactory</span><span class="params">(Resource resource)</span> <span class="keyword">throws</span> BeansException </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>(resource, (BeanFactory)<span class="keyword">null</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">XmlBeanFactory</span><span class="params">(Resource resource, BeanFactory parentBeanFactory)</span> <span class="keyword">throws</span> BeansException </span>&#123;</span><br><span class="line">        <span class="keyword">super</span>(parentBeanFactory);</span><br><span class="line">        <span class="keyword">this</span>.reader = <span class="keyword">new</span> XmlBeanDefinitionReader(<span class="keyword">this</span>);</span><br><span class="line">        <span class="keyword">this</span>.reader.loadBeanDefinitions(resource);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//根据Xml配置文件创建Resource资源对象，该对象中包含了BeanDefinition的信息</span></span><br><span class="line">ClassPathResource resource =<span class="keyword">new</span> ClassPathResource(<span class="string">"application-context.xml"</span>);</span><br><span class="line"><span class="comment">//创建DefaultListableBeanFactory</span></span><br><span class="line">DefaultListableBeanFactory factory =<span class="keyword">new</span> DefaultListableBeanFactory();</span><br><span class="line"><span class="comment">//创建XmlBeanDefinitionReader读取器，用于载入BeanDefinition。之所以需要BeanFactory作为参数，是因为会将读取的信息回调配置给factory</span></span><br><span class="line">XmlBeanDefinitionReader reader =<span class="keyword">new</span> XmlBeanDefinitionReader(factory);</span><br><span class="line"><span class="comment">//XmlBeanDefinitionReader执行载入BeanDefinition的方法，最后会完成Bean的载入和注册。完成后Bean就成功的放置到IOC容器当中，以后我们就可以从中取得Bean来使用</span></span><br><span class="line">reader.loadBeanDefinitions(resource);</span><br></pre></td></tr></table></figure>
<p>通过前面的源码，this.reader = new XmlBeanDefinitionReader(this); 中其中this 传的是factory对象</p>
<h3 id="2、FileSystemXmlApplicationContext-的IOC容器流程"><a href="#2、FileSystemXmlApplicationContext-的IOC容器流程" class="headerlink" title="2、FileSystemXmlApplicationContext 的IOC容器流程"></a>2、FileSystemXmlApplicationContext 的IOC容器流程</h3><h4 id="1-高富帅IOC解剖"><a href="#1-高富帅IOC解剖" class="headerlink" title="(1) 高富帅IOC解剖"></a>(1) 高富帅IOC解剖</h4><p>ApplicationContext =new FileSystemXmlApplicationContext(xmlPath);</p>
<p>先看其构造函数：</p>
<p>调用构造函数：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">FileSystemXmlApplicationContext</span><span class="params">(String... configLocations)</span> <span class="keyword">throws</span> BeansException </span>&#123;</span><br><span class="line">    <span class="keyword">this</span>(configLocations, <span class="keyword">true</span>, (ApplicationContext)<span class="keyword">null</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>实际调用</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">FileSystemXmlApplicationContext</span><span class="params">(String[] configLocations, <span class="keyword">boolean</span> refresh, @Nullable ApplicationContext parent)</span> <span class="keyword">throws</span> BeansException </span>&#123;</span><br><span class="line">    <span class="keyword">super</span>(parent);</span><br><span class="line">    <span class="keyword">this</span>.setConfigLocations(configLocations);</span><br><span class="line">    <span class="keyword">if</span> (refresh) &#123;</span><br><span class="line">        <span class="keyword">this</span>.refresh();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="2-设置资源加载器和资源定位"><a href="#2-设置资源加载器和资源定位" class="headerlink" title="(2) 设置资源加载器和资源定位"></a>(2) 设置资源加载器和资源定位</h4><p>通过分析FileSystemXmlApplicationContext的源代码可以知道，在创建FileSystemXmlApplicationContext容器时，构造方法做以下两项重要工作：</p>
<p>首先，调用父类容器的构造方法(super(parent)方法)为容器设置好Bean资源加载器。</p>
<p>然后，再调用父类AbstractRefreshableConfigApplicationContext的setConfigLocations(configLocations)方法设置Bean定义资源文件的定位路径。</p>
<p>通过追踪FileSystemXmlApplicationContext的继承体系，发现其父类的父类AbstractApplicationContext中初始化IoC容器所做的主要源码如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">abstract</span> <span class="class"><span class="keyword">class</span> <span class="title">AbstractApplicationContext</span> <span class="keyword">extends</span> <span class="title">DefaultResourceLoader</span> <span class="keyword">implements</span> <span class="title">ConfigurableApplicationContext</span> </span>&#123;</span><br><span class="line">    <span class="comment">//静态初始化块，在整个容器创建过程中只执行一次  </span></span><br><span class="line">    <span class="keyword">static</span> &#123;</span><br><span class="line">        <span class="comment">//为了避免应用程序在Weblogic8.1关闭时出现类加载异常加载问题，加载IoC容器关闭事件(ContextClosedEvent)类  </span></span><br><span class="line">        ContextClosedEvent.class.getName();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//FileSystemXmlApplicationContext调用父类构造方法调用的就是该方法  </span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">AbstractApplicationContext</span><span class="params">(@Nullable ApplicationContext parent)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>();</span><br><span class="line">        <span class="keyword">this</span>.setParent(parent);</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">AbstractApplicationContext</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.logger = LogFactory.getLog(<span class="keyword">this</span>.getClass());</span><br><span class="line">        <span class="keyword">this</span>.id = ObjectUtils.identityToString(<span class="keyword">this</span>);</span><br><span class="line">        <span class="keyword">this</span>.displayName = ObjectUtils.identityToString(<span class="keyword">this</span>);</span><br><span class="line">        <span class="keyword">this</span>.beanFactoryPostProcessors = <span class="keyword">new</span> ArrayList();</span><br><span class="line">        <span class="keyword">this</span>.active = <span class="keyword">new</span> AtomicBoolean();</span><br><span class="line">        <span class="keyword">this</span>.closed = <span class="keyword">new</span> AtomicBoolean();</span><br><span class="line">        <span class="keyword">this</span>.startupShutdownMonitor = <span class="keyword">new</span> Object();</span><br><span class="line">        <span class="keyword">this</span>.applicationListeners = <span class="keyword">new</span> LinkedHashSet();</span><br><span class="line">        <span class="keyword">this</span>.resourcePatternResolver = <span class="keyword">this</span>.getResourcePatternResolver();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//获取一个Spring Source的加载器用于读入Spring Bean定义资源文件  </span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> ResourcePatternResolver <span class="title">getResourcePatternResolver</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="comment">// AbstractApplicationContext继承DefaultResourceLoader，也是一个Spring资源加载器，其getResource(String location)方法用于载入资源</span></span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> PathMatchingResourcePatternResolver(<span class="keyword">this</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setParent</span><span class="params">(@Nullable ApplicationContext parent)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.parent = parent;</span><br><span class="line">        <span class="keyword">if</span> (parent != <span class="keyword">null</span>) &#123;</span><br><span class="line">            Environment parentEnvironment = parent.getEnvironment();</span><br><span class="line">            <span class="keyword">if</span> (parentEnvironment <span class="keyword">instanceof</span> ConfigurableEnvironment) &#123;</span><br><span class="line">                <span class="keyword">this</span>.getEnvironment().merge((ConfigurableEnvironment)parentEnvironment);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>AbstractApplicationContext构造方法中调用PathMatchingResourcePatternResolver的构造方法创建Spring资源加载器：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">PathMatchingResourcePatternResolver</span><span class="params">(ResourceLoader resourceLoader)</span> </span>&#123;</span><br><span class="line">    Assert.notNull(resourceLoader, <span class="string">"ResourceLoader must not be null"</span>);</span><br><span class="line">    <span class="comment">//设置Spring的资源加载器  </span></span><br><span class="line">    <span class="keyword">this</span>.resourceLoader = resourceLoader;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>在设置容器的资源加载器之后，接下来FileSystemXmlApplicationContet执行setConfigLocations方法通过调用其父类AbstractRefreshableConfigApplicationContext的方法进行对Bean定义资源文件的定位，该方法的源码如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//处理单个资源文件路径为一个字符串的情况  </span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setConfigLocation</span><span class="params">(String location)</span> </span>&#123;</span><br><span class="line">    <span class="comment">//String CONFIG_LOCATION_DELIMITERS = ",; /t/n";  </span></span><br><span class="line">    <span class="comment">//即多个资源文件路径之间用” ,; /t/n”分隔，解析成数组形式 </span></span><br><span class="line">    <span class="keyword">this</span>.setConfigLocations(StringUtils.tokenizeToStringArray(location, <span class="string">",; \t\n"</span>));</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//解析Bean定义资源文件的路径，处理多个资源文件字符串数组  </span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setConfigLocations</span><span class="params">(@Nullable String... locations)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (locations != <span class="keyword">null</span>) &#123;</span><br><span class="line">        Assert.noNullElements(locations, <span class="string">"Config locations must not be null"</span>);</span><br><span class="line">        <span class="keyword">this</span>.configLocations = <span class="keyword">new</span> String[locations.length];</span><br><span class="line"></span><br><span class="line">        <span class="keyword">for</span>(<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; locations.length; ++i) &#123;</span><br><span class="line">            <span class="comment">// resolvePath为同一个类中将字符串解析为路径的方法 </span></span><br><span class="line">            <span class="keyword">this</span>.configLocations[i] = <span class="keyword">this</span>.resolvePath(locations[i]).trim();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="keyword">this</span>.configLocations = <span class="keyword">null</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>通过这两个方法的源码我们可以看出，我们既可以使用一个字符串来配置多个Spring Bean定义资源文件，也可以使用字符串数组，即下面两种方式都是可以的：</p>
<ul>
<li>a. ClasspathResource res = new ClasspathResource(“a.xml,b.xml,……”);多个资源文件路径之间可以是用” ,; /t/n”等分隔。</li>
<li>b. ClasspathResource res = new ClasspathResource(newString[]{“a.xml”,”b.xml”,……});</li>
</ul>
<p>至此，Spring IoC容器在初始化时将配置的Bean定义资源文件定位为Spring封装的Resource。</p>
<h4 id="（3）AbstractApplicationContext的refresh函数载入Bean定义过程："><a href="#（3）AbstractApplicationContext的refresh函数载入Bean定义过程：" class="headerlink" title="（3）AbstractApplicationContext的refresh函数载入Bean定义过程："></a>（3）AbstractApplicationContext的refresh函数载入Bean定义过程：</h4><p>Spring IoC容器对Bean定义资源的载入是从refresh()函数开始的，refresh()是一个模板方法，refresh()方法的作用是：在创建IoC容器前，如果已经有容器存在，则需要把已有的容器销毁和关闭，以保证在refresh之后使用的是新建立起来的IoC容器。refresh的作用类似于对IoC容器的重启，在新建立好的容器中对容器进行初始化，对Bean定义资源进行载入</p>
<p>FileSystemXmlApplicationContext通过调用其父类AbstractApplicationContext的refresh()函数启动整个IoC容器对Bean定义的载入过程：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">refresh</span><span class="params">()</span> <span class="keyword">throws</span> BeansException, IllegalStateException </span>&#123;</span><br><span class="line">    <span class="keyword">synchronized</span>(<span class="keyword">this</span>.startupShutdownMonitor) &#123;</span><br><span class="line">        <span class="comment">//调用容器准备刷新的方法，获取容器的当时时间，同时给容器设置同步标识  </span></span><br><span class="line">        <span class="keyword">this</span>.prepareRefresh();</span><br><span class="line">        <span class="comment">//告诉子类启动refreshBeanFactory()方法，Bean定义资源文件的载入从子类的refreshBeanFactory()方法启动  </span></span><br><span class="line">        ConfigurableListableBeanFactory beanFactory = <span class="keyword">this</span>.obtainFreshBeanFactory();</span><br><span class="line">        <span class="comment">//为BeanFactory配置容器特性，例如类加载器、事件处理器等 </span></span><br><span class="line">        <span class="keyword">this</span>.prepareBeanFactory(beanFactory);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="comment">//为容器的某些子类指定特殊的BeanPost事件处理器  </span></span><br><span class="line">            <span class="keyword">this</span>.postProcessBeanFactory(beanFactory);</span><br><span class="line">            <span class="comment">//调用所有注册的BeanFactoryPostProcessor的Bean </span></span><br><span class="line">            <span class="keyword">this</span>.invokeBeanFactoryPostProcessors(beanFactory);</span><br><span class="line">            <span class="comment">//为BeanFactory注册BeanPost事件处理器.BeanPostProcessor是Bean后置处理器，用于监听容器触发的事件  </span></span><br><span class="line">            <span class="keyword">this</span>.registerBeanPostProcessors(beanFactory);</span><br><span class="line">            <span class="comment">//初始化信息源，和国际化相关. </span></span><br><span class="line">            <span class="keyword">this</span>.initMessageSource();</span><br><span class="line">            <span class="comment">//初始化容器事件传播器.  </span></span><br><span class="line">            <span class="keyword">this</span>.initApplicationEventMulticaster();</span><br><span class="line">            <span class="comment">//调用子类的某些特殊Bean初始化方法 </span></span><br><span class="line">            <span class="keyword">this</span>.onRefresh();</span><br><span class="line">            <span class="comment">//为事件传播器注册事件监听器. </span></span><br><span class="line">            <span class="keyword">this</span>.registerListeners();</span><br><span class="line">            <span class="comment">//初始化所有剩余的单态Bean.  </span></span><br><span class="line">            <span class="keyword">this</span>.finishBeanFactoryInitialization(beanFactory);</span><br><span class="line">            <span class="comment">//初始化容器的生命周期事件处理器，并发布容器的生命周期事件 </span></span><br><span class="line">            <span class="keyword">this</span>.finishRefresh();</span><br><span class="line">        &#125; <span class="keyword">catch</span> (BeansException var9) &#123;</span><br><span class="line">            <span class="keyword">if</span> (<span class="keyword">this</span>.logger.isWarnEnabled()) &#123;</span><br><span class="line">                <span class="keyword">this</span>.logger.warn(<span class="string">"Exception encountered during context initialization - cancelling refresh attempt: "</span> + var9);</span><br><span class="line">            &#125;</span><br><span class="line">			<span class="comment">//销毁以创建的单态Bean  </span></span><br><span class="line">            <span class="keyword">this</span>.destroyBeans();</span><br><span class="line">            <span class="comment">//取消refresh操作，重置容器的同步标识.  </span></span><br><span class="line">            <span class="keyword">this</span>.cancelRefresh(var9);</span><br><span class="line">            <span class="keyword">throw</span> var9;</span><br><span class="line">        &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">            <span class="keyword">this</span>.resetCommonCaches();</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>refresh()方法主要为IoC容器Bean的生命周期管理提供条件，Spring IoC容器载入Bean定义资源文件从其子类容器的refreshBeanFactory()方法启动，所以整个refresh()中“ConfigurableListableBeanFactory beanFactory =obtainFreshBeanFactory();”这句以后代码的都是注册容器的信息源和生命周期事件，载入过程就是从这句代码启动。</p>
<p>refresh()方法的作用是：在创建IoC容器前，如果已经有容器存在，则需要把已有的容器销毁和关闭，以保证在refresh之后使用的是新建立起来的IoC容器。refresh的作用类似于对IoC容器的重启，在新建立好的容器中对容器进行初始化，对Bean定义资源进行载入.</p>
<p>AbstractApplicationContext的obtainFreshBeanFactory()方法调用子类容器的refreshBeanFactory()方法，启动容器载入Bean定义资源文件的过程，代码如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> ConfigurableListableBeanFactory <span class="title">obtainFreshBeanFactory</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="comment">//这里使用了委派设计模式，父类定义了抽象的refreshBeanFactory()方法，具体实现调用子类容器的refreshBeanFactory()方法</span></span><br><span class="line">    <span class="keyword">this</span>.refreshBeanFactory();</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">this</span>.getBeanFactory();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="（4）AbstractApplicationContext子类的refreshBeanFactory-方法："><a href="#（4）AbstractApplicationContext子类的refreshBeanFactory-方法：" class="headerlink" title="（4）AbstractApplicationContext子类的refreshBeanFactory()方法："></a>（4）AbstractApplicationContext子类的refreshBeanFactory()方法：</h4><p>AbstractApplicationContext类中只抽象定义了refreshBeanFactory()方法，容器真正调用的是其子类AbstractRefreshableApplicationContext实现的    refreshBeanFactory()方法，方法的源码如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">final</span> <span class="keyword">void</span> <span class="title">refreshBeanFactory</span><span class="params">()</span> <span class="keyword">throws</span> BeansException </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">this</span>.hasBeanFactory()) &#123;</span><br><span class="line">        <span class="comment">//如果已经有容器，销毁容器中的bean，关闭容器  </span></span><br><span class="line">        <span class="keyword">this</span>.destroyBeans();</span><br><span class="line">        <span class="keyword">this</span>.closeBeanFactory();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="comment">//创建IoC容器  </span></span><br><span class="line">        DefaultListableBeanFactory beanFactory = <span class="keyword">this</span>.createBeanFactory();</span><br><span class="line">        beanFactory.setSerializationId(<span class="keyword">this</span>.getId());</span><br><span class="line">        <span class="comment">//对IoC容器进行定制化，如设置启动参数，开启注解的自动装配等</span></span><br><span class="line">        <span class="keyword">this</span>.customizeBeanFactory(beanFactory);</span><br><span class="line">        <span class="comment">//调用载入Bean定义的方法，主要这里又使用了一个委派模式，在当前类中只定义了抽象的loadBeanDefinitions方法，具体的实现调用子类容器</span></span><br><span class="line">        <span class="keyword">this</span>.loadBeanDefinitions(beanFactory);</span><br><span class="line">        <span class="keyword">synchronized</span>(<span class="keyword">this</span>.beanFactoryMonitor) &#123;</span><br><span class="line">            <span class="keyword">this</span>.beanFactory = beanFactory;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125; <span class="keyword">catch</span> (IOException var5) &#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> ApplicationContextException(<span class="string">"I/O error parsing bean definition source for "</span> + <span class="keyword">this</span>.getDisplayName(), var5);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>在这个方法中，先判断BeanFactory是否存在，如果存在则先销毁beans并关闭beanFactory，接着创建DefaultListableBeanFactory，并调用loadBeanDefinitions(beanFactory)装载bean定义。</p>
<h4 id="（5）AbstractRefreshableApplicationContext子类的loadBeanDefinitions方法："><a href="#（5）AbstractRefreshableApplicationContext子类的loadBeanDefinitions方法：" class="headerlink" title="（5）AbstractRefreshableApplicationContext子类的loadBeanDefinitions方法："></a>（5）AbstractRefreshableApplicationContext子类的loadBeanDefinitions方法：</h4><p>AbstractRefreshableApplicationContext中只定义了抽象的loadBeanDefinitions方法，容器真正调用的是其子类AbstractXmlApplicationContext对该方法的实现，AbstractXmlApplicationContext的主要源码如下：</p>
<p>loadBeanDefinitions方法同样是抽象方法，是由其子类实现的，也即在AbstractXmlApplicationContext中。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">abstract</span> <span class="class"><span class="keyword">class</span> <span class="title">AbstractXmlApplicationContext</span> <span class="keyword">extends</span> <span class="title">AbstractRefreshableConfigApplicationContext</span> </span>&#123;</span><br><span class="line">    ......</span><br><span class="line">    <span class="comment">//实现父类抽象的载入Bean定义方法  </span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">loadBeanDefinitions</span><span class="params">(DefaultListableBeanFactory beanFactory)</span> <span class="keyword">throws</span> BeansException, IOException </span>&#123;</span><br><span class="line">        <span class="comment">//创建XmlBeanDefinitionReader，即创建Bean读取器，并通过回调设置到容器中去，容器使用该读取器读取Bean定义资源  </span></span><br><span class="line">        XmlBeanDefinitionReader beanDefinitionReader = <span class="keyword">new</span> XmlBeanDefinitionReader(beanFactory);</span><br><span class="line">        beanDefinitionReader.setEnvironment(<span class="keyword">this</span>.getEnvironment());</span><br><span class="line">        <span class="comment">//为Bean读取器设置Spring资源加载器，AbstractXmlApplicationContext的祖先父类AbstractApplicationContext继承DefaultResourceLoader，因此，容器本身也是一个资源加载器  </span></span><br><span class="line">        beanDefinitionReader.setResourceLoader(<span class="keyword">this</span>);</span><br><span class="line">        <span class="comment">//为Bean读取器设置SAX xml解析器  </span></span><br><span class="line">        beanDefinitionReader.setEntityResolver(<span class="keyword">new</span> ResourceEntityResolver(<span class="keyword">this</span>));</span><br><span class="line">        <span class="comment">//当Bean读取器读取Bean定义的Xml资源文件时，启用Xml的校验机制  </span></span><br><span class="line">        <span class="keyword">this</span>.initBeanDefinitionReader(beanDefinitionReader);</span><br><span class="line">        <span class="comment">//Bean读取器真正实现加载的方法</span></span><br><span class="line">        <span class="keyword">this</span>.loadBeanDefinitions(beanDefinitionReader);</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">//Xml Bean读取器加载Bean定义资源  </span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">loadBeanDefinitions</span><span class="params">(XmlBeanDefinitionReader reader)</span> <span class="keyword">throws</span> BeansException, IOException </span>&#123;</span><br><span class="line">        <span class="comment">//获取Bean定义资源的定位</span></span><br><span class="line">        Resource[] configResources = <span class="keyword">this</span>.getConfigResources();</span><br><span class="line">        <span class="keyword">if</span> (configResources != <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="comment">//Xml Bean读取器调用其父类AbstractBeanDefinitionReader读取定位的Bean定义资源 </span></span><br><span class="line">            reader.loadBeanDefinitions(configResources);</span><br><span class="line">        &#125;</span><br><span class="line">		<span class="comment">//如果子类中获取的Bean定义资源定位为空，则获取FileSystemXmlApplicationContext构造方法中setConfigLocations方法设置的资源</span></span><br><span class="line">        String[] configLocations = <span class="keyword">this</span>.getConfigLocations();</span><br><span class="line">        <span class="keyword">if</span> (configLocations != <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="comment">//Xml Bean读取器调用其父类AbstractBeanDefinitionReader读取定位的Bean定义资源  </span></span><br><span class="line">            reader.loadBeanDefinitions(configLocations);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//这里又使用了一个委托模式，调用子类的获取Bean定义资源定位的方法,该方法在ClassPathXmlApplicationContext中进行实现，对于我们举例分析源码的FileSystemXmlApplicationContext没有使用该方法 </span></span><br><span class="line">    <span class="meta">@Nullable</span></span><br><span class="line">    <span class="keyword">protected</span> Resource[] getConfigResources() &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>Xml Bean读取器(XmlBeanDefinitionReader)调用其父类AbstractBeanDefinitionReader的 reader.loadBeanDefinitions方法读取Bean定义资源。</p>
<p>由于我们使用FileSystemXmlApplicationContext作为例子分析，因此getConfigResources的返回值为null，因此程序执行reader.loadBeanDefinitions(configLocations)分支。</p>
<h4 id="（6）AbstractBeanDefinitionReader读取Bean定义资源："><a href="#（6）AbstractBeanDefinitionReader读取Bean定义资源：" class="headerlink" title="（6）AbstractBeanDefinitionReader读取Bean定义资源："></a>（6）AbstractBeanDefinitionReader读取Bean定义资源：</h4><p>AbstractBeanDefinitionReader的loadBeanDefinitions方法源码如下：</p>
<p>可以到org.springframework.beans.factory.support看一下BeanDefinitionReader的结构</p>
<p><img src="/xieyuanhui/2019/06/28/Spring-IOC源码解析/img5.jpg" alt></p>
<p>在其抽象父类AbstractBeanDefinitionReader中定义了载入过程</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//重载方法，调用下面的loadBeanDefinitions(String, Set&lt;Resource&gt;);方法  </span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">loadBeanDefinitions</span><span class="params">(String location)</span> <span class="keyword">throws</span> BeanDefinitionStoreException </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">this</span>.loadBeanDefinitions(location, (Set)<span class="keyword">null</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">loadBeanDefinitions</span><span class="params">(String location, @Nullable Set&lt;Resource&gt; actualResources)</span> <span class="keyword">throws</span> BeanDefinitionStoreException </span>&#123;</span><br><span class="line">    <span class="comment">//获取在IoC容器初始化过程中设置的资源加载器</span></span><br><span class="line">    ResourceLoader resourceLoader = <span class="keyword">this</span>.getResourceLoader();</span><br><span class="line">    <span class="keyword">if</span> (resourceLoader == <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> BeanDefinitionStoreException(<span class="string">"Cannot import bean definitions from location ["</span> + location + <span class="string">"]: no ResourceLoader available"</span>);</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="keyword">int</span> loadCount;</span><br><span class="line">        <span class="keyword">if</span> (!(resourceLoader <span class="keyword">instanceof</span> ResourcePatternResolver)) &#123;</span><br><span class="line">            <span class="comment">//将指定位置的Bean定义资源文件解析为Spring IoC容器封装的资源,加载多个指定位置的Bean定义资源文件</span></span><br><span class="line">            Resource resource = resourceLoader.getResource(location);</span><br><span class="line">            <span class="comment">//委派调用其子类XmlBeanDefinitionReader的方法，实现加载功能</span></span><br><span class="line">            loadCount = <span class="keyword">this</span>.loadBeanDefinitions((Resource)resource);</span><br><span class="line">            <span class="keyword">if</span> (actualResources != <span class="keyword">null</span>) &#123;</span><br><span class="line">                actualResources.add(resource);</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">if</span> (<span class="keyword">this</span>.logger.isDebugEnabled()) &#123;</span><br><span class="line">                <span class="keyword">this</span>.logger.debug(<span class="string">"Loaded "</span> + loadCount + <span class="string">" bean definitions from location ["</span> + location + <span class="string">"]"</span>);</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">return</span> loadCount;</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                <span class="comment">//将指定位置的Bean定义资源文件解析为Spring IoC容器封装的资源,加载单个指定位置的Bean定义资源文件  </span></span><br><span class="line">                Resource[] resources = ((ResourcePatternResolver)resourceLoader).getResources(location);</span><br><span class="line">                <span class="comment">//委派调用其子类XmlBeanDefinitionReader的方法，实现加载功能</span></span><br><span class="line">                loadCount = <span class="keyword">this</span>.loadBeanDefinitions(resources);</span><br><span class="line">                <span class="keyword">if</span> (actualResources != <span class="keyword">null</span>) &#123;</span><br><span class="line">                    Resource[] var6 = resources;</span><br><span class="line">                    <span class="keyword">int</span> var7 = resources.length;</span><br><span class="line"></span><br><span class="line">                    <span class="keyword">for</span>(<span class="keyword">int</span> var8 = <span class="number">0</span>; var8 &lt; var7; ++var8) &#123;</span><br><span class="line">                        Resource resource = var6[var8];</span><br><span class="line">                        actualResources.add(resource);</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line"></span><br><span class="line">                <span class="keyword">if</span> (<span class="keyword">this</span>.logger.isDebugEnabled()) &#123;</span><br><span class="line">                    <span class="keyword">this</span>.logger.debug(<span class="string">"Loaded "</span> + loadCount + <span class="string">" bean definitions from location pattern ["</span> + location + <span class="string">"]"</span>);</span><br><span class="line">                &#125;</span><br><span class="line"></span><br><span class="line">                <span class="keyword">return</span> loadCount;</span><br><span class="line">            &#125; <span class="keyword">catch</span> (IOException var10) &#123;</span><br><span class="line">                <span class="keyword">throw</span> <span class="keyword">new</span> BeanDefinitionStoreException(<span class="string">"Could not resolve bean definition resource pattern ["</span> + location + <span class="string">"]"</span>, var10);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//重载方法，调用loadBeanDefinitions(String); </span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">loadBeanDefinitions</span><span class="params">(String... locations)</span> <span class="keyword">throws</span> BeanDefinitionStoreException </span>&#123;</span><br><span class="line">        Assert.notNull(locations, <span class="string">"Location array must not be null"</span>);</span><br><span class="line">        <span class="keyword">int</span> counter = <span class="number">0</span>;</span><br><span class="line">        String[] var3 = locations;</span><br><span class="line">        <span class="keyword">int</span> var4 = locations.length;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">for</span>(<span class="keyword">int</span> var5 = <span class="number">0</span>; var5 &lt; var4; ++var5) &#123;</span><br><span class="line">            String location = var3[var5];</span><br><span class="line">            counter += <span class="keyword">this</span>.loadBeanDefinitions(location);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> counter;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<p>loadBeanDefinitions(Resource…resources)方法和上面分析的3个方法类似，同样也是调用XmlBeanDefinitionReader的loadBeanDefinitions方法。</p>
<p>从对AbstractBeanDefinitionReader的loadBeanDefinitions方法源码分析可以看出该方法做了以下两件事：</p>
<p>首先，调用资源加载器的获取资源方法resourceLoader.getResource(location)，获取到要加载的资源。</p>
<p>其次，真正执行加载功能是其子类XmlBeanDefinitionReader的loadBeanDefinitions方法。</p>
<p><img src="/xieyuanhui/2019/06/28/Spring-IOC源码解析/img6.jpg" alt></p>
<p>看到第8、16行，结合上面的ResourceLoader与ApplicationContext的继承关系图，可以知道此时调用的是DefaultResourceLoader中的getSource()方法定位Resource，因为FileSystemXmlApplicationContext本身就是DefaultResourceLoader的实现类，所以此时又回到了FileSystemXmlApplicationContext中来。</p>
<h4 id="（7）资源加载器获取要读入的资源："><a href="#（7）资源加载器获取要读入的资源：" class="headerlink" title="（7）资源加载器获取要读入的资源："></a>（7）资源加载器获取要读入的资源：</h4><p>XmlBeanDefinitionReader通过调用其父类DefaultResourceLoader的getResource方法获取要加载的资源，其源码如下</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//获取Resource的具体实现方法</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> Resource <span class="title">getResource</span><span class="params">(String location)</span> </span>&#123;</span><br><span class="line">    Assert.notNull(location, <span class="string">"Location must not be null"</span>);</span><br><span class="line">    Iterator var2 = <span class="keyword">this</span>.protocolResolvers.iterator();</span><br><span class="line"></span><br><span class="line">    Resource resource;</span><br><span class="line">    <span class="keyword">do</span> &#123;</span><br><span class="line">        <span class="comment">//如果是类路径的方式，那需要使用ClassPathResource 来得到bean文件的资源对象</span></span><br><span class="line">        <span class="keyword">if</span> (!var2.hasNext()) &#123;</span><br><span class="line">            <span class="keyword">if</span> (location.startsWith(<span class="string">"/"</span>)) &#123;</span><br><span class="line">                <span class="keyword">return</span> <span class="keyword">this</span>.getResourceByPath(location);</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">if</span> (location.startsWith(<span class="string">"classpath:"</span>)) &#123;</span><br><span class="line">                <span class="keyword">return</span> <span class="keyword">new</span> ClassPathResource(location.substring(<span class="string">"classpath:"</span>.length()), <span class="keyword">this</span>.getClassLoader());</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                <span class="comment">// 如果是URL 方式，使用UrlResource 作为bean 文件的资源对象</span></span><br><span class="line">                URL url = <span class="keyword">new</span> URL(location);</span><br><span class="line">                <span class="keyword">return</span> (Resource)(ResourceUtils.isFileURL(url) ? <span class="keyword">new</span> FileUrlResource(url) : <span class="keyword">new</span> UrlResource(url));</span><br><span class="line">            &#125; <span class="keyword">catch</span> (MalformedURLException var5) &#123;</span><br><span class="line">                <span class="comment">//如果既不是classpath标识，又不是URL标识的Resource定位，则调用容器本身的getResourceByPath方法获取Resource</span></span><br><span class="line">                <span class="keyword">return</span> <span class="keyword">this</span>.getResourceByPath(location);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        ProtocolResolver protocolResolver = (ProtocolResolver)var2.next();</span><br><span class="line">        resource = protocolResolver.resolve(location, <span class="keyword">this</span>);</span><br><span class="line">    &#125; <span class="keyword">while</span>(resource == <span class="keyword">null</span>);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> resource;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>FileSystemXmlApplicationContext容器提供了getResourceByPath方法的实现，就是为了处理既不是classpath标识，又不是URL标识的Resource定位这种情况。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> Resource <span class="title">getResourceByPath</span><span class="params">(String path)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (path.startsWith(<span class="string">"/"</span>)) &#123;</span><br><span class="line">        path = path.substring(<span class="number">1</span>);</span><br><span class="line">    &#125;</span><br><span class="line">	<span class="comment">//这里使用文件系统资源对象来定义bean文件</span></span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> FileSystemResource(path);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这样代码就回到了 FileSystemXmlApplicationContext 中来，他提供了FileSystemResource 来完成从文件系统得到配置文件的资源定义。</p>
<p>这样，就可以从文件系统路径上对IOC 配置文件进行加载 - 当然我们可以按照这个逻辑从任何地方加载，在Spring 中我们看到它提供 的各种资源抽象，比如ClassPathResource, URLResource,FileSystemResource 等来供我们使用。上面我们看到的是定位Resource 的一个过程，而这只是加载过程的一部分.</p>
<h4 id="（8）XmlBeanDefinitionReader加载Bean定义资源："><a href="#（8）XmlBeanDefinitionReader加载Bean定义资源：" class="headerlink" title="（8）XmlBeanDefinitionReader加载Bean定义资源："></a>（8）XmlBeanDefinitionReader加载Bean定义资源：</h4><p>Bean定义的Resource得到了</p>
<p>继续回到XmlBeanDefinitionReader的loadBeanDefinitions(Resource …)方法看到代表bean文件的资源定义以后的载入过程。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//XmlBeanDefinitionReader加载资源的入口方法  </span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">loadBeanDefinitions</span><span class="params">(Resource resource)</span> <span class="keyword">throws</span> BeanDefinitionStoreException </span>&#123;</span><br><span class="line">    <span class="comment">//将读入的XML资源进行特殊编码处理</span></span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">this</span>.loadBeanDefinitions(<span class="keyword">new</span> EncodedResource(resource));</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//这里是载入XML形式Bean定义资源文件方法</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">loadBeanDefinitions</span><span class="params">(EncodedResource encodedResource)</span> <span class="keyword">throws</span> BeanDefinitionStoreException </span>&#123;</span><br><span class="line">    Assert.notNull(encodedResource, <span class="string">"EncodedResource must not be null"</span>);</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">this</span>.logger.isInfoEnabled()) &#123;</span><br><span class="line">        <span class="keyword">this</span>.logger.info(<span class="string">"Loading XML bean definitions from "</span> + encodedResource);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    Set&lt;EncodedResource&gt; currentResources = (Set)<span class="keyword">this</span>.resourcesCurrentlyBeingLoaded.get();</span><br><span class="line">    <span class="keyword">if</span> (currentResources == <span class="keyword">null</span>) &#123;</span><br><span class="line">        currentResources = <span class="keyword">new</span> HashSet(<span class="number">4</span>);</span><br><span class="line">        <span class="keyword">this</span>.resourcesCurrentlyBeingLoaded.set(currentResources);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (!((Set)currentResources).add(encodedResource)) &#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> BeanDefinitionStoreException(<span class="string">"Detected cyclic loading of "</span> + encodedResource + <span class="string">" - check your import definitions!"</span>);</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="keyword">int</span> var5;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="comment">//将资源文件转为InputStream的IO流 </span></span><br><span class="line">            InputStream inputStream = encodedResource.getResource().getInputStream();</span><br><span class="line"></span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                <span class="comment">//从InputStream中得到XML的解析源</span></span><br><span class="line">                InputSource inputSource = <span class="keyword">new</span> InputSource(inputStream);</span><br><span class="line">                <span class="keyword">if</span> (encodedResource.getEncoding() != <span class="keyword">null</span>) &#123;</span><br><span class="line">                    inputSource.setEncoding(encodedResource.getEncoding());</span><br><span class="line">                &#125;</span><br><span class="line">	<span class="comment">//这里是具体的读取过程 </span></span><br><span class="line">                var5 = <span class="keyword">this</span>.doLoadBeanDefinitions(inputSource, encodedResource.getResource());</span><br><span class="line">            &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">                inputStream.close();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; <span class="keyword">catch</span> (IOException var15) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> BeanDefinitionStoreException(<span class="string">"IOException parsing XML document from "</span> + encodedResource.getResource(), var15);</span><br><span class="line">        &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">            ((Set)currentResources).remove(encodedResource);</span><br><span class="line">            <span class="keyword">if</span> (((Set)currentResources).isEmpty()) &#123;</span><br><span class="line">                <span class="keyword">this</span>.resourcesCurrentlyBeingLoaded.remove();</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> var5;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//从特定XML文件中实际载入Bean定义资源的方法 </span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">int</span> <span class="title">doLoadBeanDefinitions</span><span class="params">(InputSource inputSource, Resource resource)</span> <span class="keyword">throws</span> BeanDefinitionStoreException </span>&#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="comment">//将XML文件转换为DOM对象，解析过程由documentLoader实现</span></span><br><span class="line">            Document doc = <span class="keyword">this</span>.doLoadDocument(inputSource, resource);</span><br><span class="line">            <span class="comment">//这里是启动对Bean定义解析的详细过程，该解析过程会用到Spring的Bean配置规则</span></span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">this</span>.registerBeanDefinitions(doc, resource);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (BeanDefinitionStoreException var4) &#123;</span><br><span class="line">            <span class="keyword">throw</span> var4;</span><br><span class="line">        &#125; <span class="keyword">catch</span> (SAXParseException var5) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> XmlBeanDefinitionStoreException(resource.getDescription(), <span class="string">"Line "</span> + var5.getLineNumber() + <span class="string">" in XML document from "</span> + resource + <span class="string">" is invalid"</span>, var5);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (SAXException var6) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> XmlBeanDefinitionStoreException(resource.getDescription(), <span class="string">"XML document from "</span> + resource + <span class="string">" is invalid"</span>, var6);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (ParserConfigurationException var7) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> BeanDefinitionStoreException(resource.getDescription(), <span class="string">"Parser configuration exception parsing XML from "</span> + resource, var7);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (IOException var8) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> BeanDefinitionStoreException(resource.getDescription(), <span class="string">"IOException parsing XML document from "</span> + resource, var8);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Throwable var9) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> BeanDefinitionStoreException(resource.getDescription(), <span class="string">"Unexpected exception parsing XML document from "</span> + resource, var9);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<p>通过源码分析，载入Bean定义资源文件的最后一步是将Bean定义资源转换为Document对象，该过程由documentLoader实现</p>
<h4 id="（9）DocumentLoader将Bean定义资源转换为Document对象："><a href="#（9）DocumentLoader将Bean定义资源转换为Document对象：" class="headerlink" title="（9）DocumentLoader将Bean定义资源转换为Document对象："></a>（9）DocumentLoader将Bean定义资源转换为Document对象：</h4><p>DocumentLoader将Bean定义资源转换成Document对象的源码如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//使用标准的JAXP将载入的Bean定义资源转换成document对象  </span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> Document <span class="title">loadDocument</span><span class="params">(InputSource inputSource, EntityResolver entityResolver,  </span></span></span><br><span class="line"><span class="function"><span class="params">           ErrorHandler errorHandler, <span class="keyword">int</span> validationMode, <span class="keyword">boolean</span> namespaceAware)</span> <span class="keyword">throws</span> Exception </span>&#123;  </span><br><span class="line">       <span class="comment">//创建文件解析器工厂  </span></span><br><span class="line">       DocumentBuilderFactory factory = createDocumentBuilderFactory(validationMode, namespaceAware);  </span><br><span class="line">       <span class="keyword">if</span> (logger.isDebugEnabled()) &#123;  </span><br><span class="line">           logger.debug(<span class="string">"Using JAXP provider ["</span> + factory.getClass().getName() + <span class="string">"]"</span>);  </span><br><span class="line">       &#125;  </span><br><span class="line">       <span class="comment">//创建文档解析器  </span></span><br><span class="line">       DocumentBuilder builder = createDocumentBuilder(factory, entityResolver, errorHandler);  </span><br><span class="line">       <span class="comment">//解析Spring的Bean定义资源  </span></span><br><span class="line">       <span class="keyword">return</span> builder.parse(inputSource);  </span><br><span class="line">   &#125;  </span><br><span class="line">   <span class="function"><span class="keyword">protected</span> DocumentBuilderFactory <span class="title">createDocumentBuilderFactory</span><span class="params">(<span class="keyword">int</span> validationMode, <span class="keyword">boolean</span> namespaceAware)</span>  </span></span><br><span class="line"><span class="function">           <span class="keyword">throws</span> ParserConfigurationException </span>&#123;  </span><br><span class="line">       <span class="comment">//创建文档解析工厂  </span></span><br><span class="line">       DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();  </span><br><span class="line">       factory.setNamespaceAware(namespaceAware);  </span><br><span class="line">       <span class="comment">//设置解析XML的校验  </span></span><br><span class="line">       <span class="keyword">if</span> (validationMode != XmlValidationModeDetector.VALIDATION_NONE) &#123;  </span><br><span class="line">           factory.setValidating(<span class="keyword">true</span>);  </span><br><span class="line">           <span class="keyword">if</span> (validationMode == XmlValidationModeDetector.VALIDATION_XSD) &#123;  </span><br><span class="line">               factory.setNamespaceAware(<span class="keyword">true</span>);  </span><br><span class="line">               <span class="keyword">try</span> &#123;  </span><br><span class="line">                   factory.setAttribute(SCHEMA_LANGUAGE_ATTRIBUTE, XSD_SCHEMA_LANGUAGE);  </span><br><span class="line">               &#125;  </span><br><span class="line">               <span class="keyword">catch</span> (IllegalArgumentException ex) &#123;  </span><br><span class="line">                   ParserConfigurationException pcex = <span class="keyword">new</span> ParserConfigurationException(  </span><br><span class="line">                           <span class="string">"Unable to validate using XSD: Your JAXP provider ["</span> + factory +  </span><br><span class="line">                           <span class="string">"] does not support XML Schema. Are you running on Java 1.4 with Apache Crimson? "</span> +  </span><br><span class="line">                           <span class="string">"Upgrade to Apache Xerces (or Java 1.5) for full XSD support."</span>);  </span><br><span class="line">                   pcex.initCause(ex);  </span><br><span class="line">                   <span class="keyword">throw</span> pcex;  </span><br><span class="line">               &#125;  </span><br><span class="line">           &#125;  </span><br><span class="line">       &#125;  </span><br><span class="line">       <span class="keyword">return</span> factory;  </span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>
<p>该解析过程调用JavaEE标准的JAXP标准进行处理。</p>
<p>至此Spring IoC容器根据定位的Bean定义资源文件，将其加载读入并转换成为Document对象过程完成。</p>
<p>接下来我们要继续分析Spring IoC容器将载入的Bean定义资源文件转换为Document对象之后，是如何将其解析为Spring IoC管理的Bean对象并将其注册到容器中的。</p>
<h4 id="（10）XmlBeanDefinitionReader解析载入的Bean定义资源文件："><a href="#（10）XmlBeanDefinitionReader解析载入的Bean定义资源文件：" class="headerlink" title="（10）XmlBeanDefinitionReader解析载入的Bean定义资源文件："></a>（10）XmlBeanDefinitionReader解析载入的Bean定义资源文件：</h4><p>XmlBeanDefinitionReader类中的doLoadBeanDefinitions方法是从特定XML文件中实际载入Bean定义资源的方法，该方法在载入Bean定义资源之后将其转换为Document对象，接下来调用registerBeanDefinitions启动Spring IoC容器对Bean定义的解析过程，registerBeanDefinitions方法源码如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//按照Spring的Bean语义要求将Bean定义资源解析并转换为容器内部数据结构</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">registerBeanDefinitions</span><span class="params">(Document doc, Resource resource)</span> <span class="keyword">throws</span> BeanDefinitionStoreException </span>&#123;</span><br><span class="line">    <span class="comment">//得到BeanDefinitionDocumentReader来对xml格式的BeanDefinition解析 </span></span><br><span class="line">    BeanDefinitionDocumentReader documentReader = <span class="keyword">this</span>.createBeanDefinitionDocumentReader();</span><br><span class="line">    <span class="comment">//获得容器中注册的Bean数量 </span></span><br><span class="line">    <span class="keyword">int</span> countBefore = <span class="keyword">this</span>.getRegistry().getBeanDefinitionCount();</span><br><span class="line">    <span class="comment">//解析过程入口，这里使用了委派模式，BeanDefinitionDocumentReader只是个接口，//具体的解析实现过程有实现类DefaultBeanDefinitionDocumentReader完成</span></span><br><span class="line">    documentReader.registerBeanDefinitions(doc, <span class="keyword">this</span>.createReaderContext(resource));</span><br><span class="line">    <span class="comment">//统计解析的Bean数量 </span></span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">this</span>.getRegistry().getBeanDefinitionCount() - countBefore;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//创建BeanDefinitionDocumentReader对象，解析Document对象</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> BeanDefinitionDocumentReader <span class="title">createBeanDefinitionDocumentReader</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> (BeanDefinitionDocumentReader)BeanUtils.instantiateClass(<span class="keyword">this</span>.documentReaderClass);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>Bean定义资源的载入解析分为以下两个过程：</p>
<p>首先，通过调用XML解析器将Bean定义资源文件转换得到Document对象，但是这些Document对象并没有按照Spring的Bean规则进行解析。这一步是载入的过程</p>
<p>其次，在完成通用的XML解析之后，按照Spring的Bean规则对Document对象进行解析。</p>
<p>按照Spring的Bean规则对Document对象解析的过程是在接口BeanDefinitionDocumentReader的实现类DefaultBeanDefinitionDocumentReader中实现的。</p>
<h4 id="（11）DefaultBeanDefinitionDocumentReader对Bean定义的Document对象解析："><a href="#（11）DefaultBeanDefinitionDocumentReader对Bean定义的Document对象解析：" class="headerlink" title="（11）DefaultBeanDefinitionDocumentReader对Bean定义的Document对象解析："></a>（11）DefaultBeanDefinitionDocumentReader对Bean定义的Document对象解析：</h4><p>BeanDefinitionDocumentReader接口通过registerBeanDefinitions方法调用其实现类DefaultBeanDefinitionDocumentReader对Document对象进行解析，解析的代码如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br><span class="line">181</span><br><span class="line">182</span><br><span class="line">183</span><br><span class="line">184</span><br><span class="line">185</span><br><span class="line">186</span><br><span class="line">187</span><br><span class="line">188</span><br><span class="line">189</span><br><span class="line">190</span><br><span class="line">191</span><br><span class="line">192</span><br><span class="line">193</span><br><span class="line">194</span><br><span class="line">195</span><br><span class="line">196</span><br><span class="line">197</span><br><span class="line">198</span><br><span class="line">199</span><br><span class="line">200</span><br><span class="line">201</span><br><span class="line">202</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//根据Spring DTD对Bean的定义规则解析Bean定义Document对象</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">registerBeanDefinitions</span><span class="params">(Document doc, XmlReaderContext readerContext)</span> </span>&#123;</span><br><span class="line">    <span class="comment">//获得XML描述符</span></span><br><span class="line">    <span class="keyword">this</span>.readerContext = readerContext;</span><br><span class="line">    <span class="keyword">this</span>.logger.debug(<span class="string">"Loading bean definitions"</span>);</span><br><span class="line">    <span class="comment">//获得Document的根元素</span></span><br><span class="line">    Element root = doc.getDocumentElement();</span><br><span class="line">    <span class="keyword">this</span>.doRegisterBeanDefinitions(root);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">doRegisterBeanDefinitions</span><span class="params">(Element root)</span> </span>&#123;</span><br><span class="line">    <span class="comment">//具体的解析过程由BeanDefinitionParserDelegate实现，BeanDefinitionParserDelegate中定义了Spring Bean定义XML文件的各种元素    </span></span><br><span class="line">    BeanDefinitionParserDelegate parent = <span class="keyword">this</span>.delegate;</span><br><span class="line">        <span class="keyword">this</span>.delegate = <span class="keyword">this</span>.createDelegate(<span class="keyword">this</span>.getReaderContext(), root, parent);</span><br><span class="line">        <span class="keyword">if</span> (<span class="keyword">this</span>.delegate.isDefaultNamespace(root)) &#123;</span><br><span class="line">            String profileSpec = root.getAttribute(<span class="string">"profile"</span>);</span><br><span class="line">            <span class="keyword">if</span> (StringUtils.hasText(profileSpec)) &#123;</span><br><span class="line">                String[] specifiedProfiles = StringUtils.tokenizeToStringArray(profileSpec, <span class="string">",; "</span>);</span><br><span class="line">                <span class="keyword">if</span> (!<span class="keyword">this</span>.getReaderContext().getEnvironment().acceptsProfiles(specifiedProfiles)) &#123;</span><br><span class="line">                    <span class="keyword">if</span> (<span class="keyword">this</span>.logger.isInfoEnabled()) &#123;</span><br><span class="line">                        <span class="keyword">this</span>.logger.info(<span class="string">"Skipped XML bean definition file due to specified profiles ["</span> + profileSpec + <span class="string">"] not matching: "</span> + <span class="keyword">this</span>.getReaderContext().getResource());</span><br><span class="line">                    &#125;</span><br><span class="line"></span><br><span class="line">                    <span class="keyword">return</span>;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">		<span class="comment">//在解析Bean定义之前，进行自定义的解析，增强解析过程的可扩展性</span></span><br><span class="line">        <span class="keyword">this</span>.preProcessXml(root);</span><br><span class="line">    	<span class="comment">//从Document的根元素开始进行Bean定义的Document对象 </span></span><br><span class="line">        <span class="keyword">this</span>.parseBeanDefinitions(root, <span class="keyword">this</span>.delegate);</span><br><span class="line">    	<span class="comment">//在解析Bean定义之后，进行自定义的解析，增加解析过程的可扩展性</span></span><br><span class="line">        <span class="keyword">this</span>.postProcessXml(root);</span><br><span class="line">        <span class="keyword">this</span>.delegate = parent;</span><br><span class="line">    &#125;</span><br><span class="line"><span class="comment">//创建BeanDefinitionParserDelegate，用于完成真正的解析过程 </span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> BeanDefinitionParserDelegate <span class="title">createDelegate</span><span class="params">(XmlReaderContext readerContext, Element root, @Nullable BeanDefinitionParserDelegate parentDelegate)</span> </span>&#123;</span><br><span class="line">        BeanDefinitionParserDelegate delegate = <span class="keyword">new</span> BeanDefinitionParserDelegate(readerContext);</span><br><span class="line">    	<span class="comment">//BeanDefinitionParserDelegate初始化Document根元素</span></span><br><span class="line">        delegate.initDefaults(root, parentDelegate);</span><br><span class="line">        <span class="keyword">return</span> delegate;</span><br><span class="line">    &#125;</span><br><span class="line"><span class="comment">//使用Spring的Bean规则从Document的根元素开始进行Bean定义的Document对象</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">parseBeanDefinitions</span><span class="params">(Element root, BeanDefinitionParserDelegate delegate)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (delegate.isDefaultNamespace(root)) &#123;</span><br><span class="line">            <span class="comment">//使用Spring的Bean规则从Document的根元素开始进行Bean定义的Document对象</span></span><br><span class="line">            NodeList nl = root.getChildNodes();</span><br><span class="line"></span><br><span class="line">            <span class="keyword">for</span>(<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; nl.getLength(); ++i) &#123;</span><br><span class="line">                Node node = nl.item(i);</span><br><span class="line">                <span class="comment">//获得Document节点是XML元素节点 </span></span><br><span class="line">                <span class="keyword">if</span> (node <span class="keyword">instanceof</span> Element) &#123;</span><br><span class="line">                    Element ele = (Element)node;</span><br><span class="line">                    <span class="comment">//Bean定义的Document的元素节点使用的是Spring默认的XML命名空间</span></span><br><span class="line">                    <span class="keyword">if</span> (delegate.isDefaultNamespace(ele)) &#123;</span><br><span class="line">                        <span class="comment">//使用Spring的Bean规则解析元素节点</span></span><br><span class="line">                        <span class="keyword">this</span>.parseDefaultElement(ele, delegate);</span><br><span class="line">                    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                        <span class="comment">//没有使用Spring默认的XML命名空间，则使用用户自定义的解//析规则解析元素节点</span></span><br><span class="line">                        delegate.parseCustomElement(ele);</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="comment">//Document的根节点没有使用Spring默认的命名空间，则使用用户自定义的解析规则解析Document根节点</span></span><br><span class="line">            delegate.parseCustomElement(root);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"><span class="comment">//使用Spring的Bean规则解析Document元素节点 </span></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">parseDefaultElement</span><span class="params">(Element ele, BeanDefinitionParserDelegate delegate)</span> </span>&#123;</span><br><span class="line">    	<span class="comment">//如果元素节点是&lt;Import&gt;导入元素，进行导入解析</span></span><br><span class="line">        <span class="keyword">if</span> (delegate.nodeNameEquals(ele, <span class="string">"import"</span>)) &#123;</span><br><span class="line">            <span class="keyword">this</span>.importBeanDefinitionResource(ele);</span><br><span class="line">        &#125; </span><br><span class="line">    <span class="comment">//如果元素节点是&lt;Alias&gt;别名元素，进行别名解析</span></span><br><span class="line">    <span class="keyword">else</span> <span class="keyword">if</span> (delegate.nodeNameEquals(ele, <span class="string">"alias"</span>)) &#123;</span><br><span class="line">            <span class="keyword">this</span>.processAliasRegistration(ele);</span><br><span class="line">        &#125;</span><br><span class="line">    <span class="comment">//元素节点既不是导入元素，也不是别名元素，即普通的&lt;Bean&gt;元素，按照Spring的Bean规则解析元素  </span></span><br><span class="line">    <span class="keyword">else</span> <span class="keyword">if</span> (delegate.nodeNameEquals(ele, <span class="string">"bean"</span>)) &#123;</span><br><span class="line">            <span class="keyword">this</span>.processBeanDefinition(ele, delegate);</span><br><span class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span> (delegate.nodeNameEquals(ele, <span class="string">"beans"</span>)) &#123;</span><br><span class="line">            <span class="keyword">this</span>.doRegisterBeanDefinitions(ele);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"><span class="comment">//解析&lt;Import&gt;导入元素，从给定的导入路径加载Bean定义资源到Spring IoC容器中</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">importBeanDefinitionResource</span><span class="params">(Element ele)</span> </span>&#123;</span><br><span class="line">    	<span class="comment">//获取给定的导入元素的location属性</span></span><br><span class="line">        String location = ele.getAttribute(<span class="string">"resource"</span>);</span><br><span class="line">    	<span class="comment">//如果导入元素的location属性值为空，则没有导入任何资源，直接返回</span></span><br><span class="line">        <span class="keyword">if</span> (!StringUtils.hasText(location)) &#123;</span><br><span class="line">            <span class="keyword">this</span>.getReaderContext().error(<span class="string">"Resource location must not be empty"</span>, ele);</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="comment">//使用系统变量值解析location属性值</span></span><br><span class="line">            location = <span class="keyword">this</span>.getReaderContext().getEnvironment().resolveRequiredPlaceholders(location);</span><br><span class="line">            Set&lt;Resource&gt; actualResources = <span class="keyword">new</span> LinkedHashSet(<span class="number">4</span>);</span><br><span class="line">            <span class="comment">//标识给定的导入元素的location是否是绝对路径</span></span><br><span class="line">            <span class="keyword">boolean</span> absoluteLocation = <span class="keyword">false</span>;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                absoluteLocation = ResourcePatternUtils.isUrl(location) || ResourceUtils.toURI(location).isAbsolute();</span><br><span class="line">            &#125; <span class="keyword">catch</span> (URISyntaxException var11) &#123;</span><br><span class="line">                <span class="comment">//给定的导入元素的location不是绝对路径 </span></span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">int</span> importCount;</span><br><span class="line">            <span class="comment">//给定的导入元素的location是绝对路径</span></span><br><span class="line">            <span class="keyword">if</span> (absoluteLocation) &#123;</span><br><span class="line">                <span class="keyword">try</span> &#123;</span><br><span class="line">                    <span class="comment">//使用资源读入器加载给定路径的Bean定义资源</span></span><br><span class="line">                    importCount = <span class="keyword">this</span>.getReaderContext().getReader().loadBeanDefinitions(location, actualResources);</span><br><span class="line">                    <span class="keyword">if</span> (<span class="keyword">this</span>.logger.isDebugEnabled()) &#123;</span><br><span class="line">                        <span class="keyword">this</span>.logger.debug(<span class="string">"Imported "</span> + importCount + <span class="string">" bean definitions from URL location ["</span> + location + <span class="string">"]"</span>);</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125; <span class="keyword">catch</span> (BeanDefinitionStoreException var10) &#123;</span><br><span class="line">                    <span class="keyword">this</span>.getReaderContext().error(<span class="string">"Failed to import bean definitions from URL location ["</span> + location + <span class="string">"]"</span>, ele, var10);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                <span class="comment">//给定的导入元素的location是相对路径</span></span><br><span class="line">                <span class="keyword">try</span> &#123;</span><br><span class="line">                    <span class="comment">//将给定导入元素的location封装为相对路径资源 </span></span><br><span class="line">                    Resource relativeResource = <span class="keyword">this</span>.getReaderContext().getResource().createRelative(location);</span><br><span class="line">                    <span class="comment">//封装的相对路径资源存在</span></span><br><span class="line">                    <span class="keyword">if</span> (relativeResource.exists()) &#123;</span><br><span class="line">                        <span class="comment">//使用资源读入器加载Bean定义资源</span></span><br><span class="line">                        importCount = <span class="keyword">this</span>.getReaderContext().getReader().loadBeanDefinitions(relativeResource);</span><br><span class="line">                        actualResources.add(relativeResource);</span><br><span class="line">                    &#125;</span><br><span class="line">                    <span class="comment">//封装的相对路径资源不存在</span></span><br><span class="line">                    <span class="keyword">else</span> &#123;</span><br><span class="line">                   <span class="comment">//获取Spring IoC容器资源读入器的基本路径</span></span><br><span class="line">                        String baseLocation = <span class="keyword">this</span>.getReaderContext().getResource().getURL().toString();</span><br><span class="line">                        <span class="comment">//根据Spring IoC容器资源读入器的基本路径加载给定导入路径的资源</span></span><br><span class="line">                        importCount = <span class="keyword">this</span>.getReaderContext().getReader().loadBeanDefinitions(StringUtils.applyRelativePath(baseLocation, location), actualResources);</span><br><span class="line">                    &#125;</span><br><span class="line"></span><br><span class="line">                    <span class="keyword">if</span> (<span class="keyword">this</span>.logger.isDebugEnabled()) &#123;</span><br><span class="line">                        <span class="keyword">this</span>.logger.debug(<span class="string">"Imported "</span> + importCount + <span class="string">" bean definitions from relative location ["</span> + location + <span class="string">"]"</span>);</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125; <span class="keyword">catch</span> (IOException var8) &#123;</span><br><span class="line">                    <span class="keyword">this</span>.getReaderContext().error(<span class="string">"Failed to resolve current resource location"</span>, ele, var8);</span><br><span class="line">                &#125; <span class="keyword">catch</span> (BeanDefinitionStoreException var9) &#123;</span><br><span class="line">                    <span class="keyword">this</span>.getReaderContext().error(<span class="string">"Failed to import bean definitions from relative location ["</span> + location + <span class="string">"]"</span>, ele, var9);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            Resource[] actResArray = (Resource[])actualResources.toArray(<span class="keyword">new</span> Resource[<span class="number">0</span>]);</span><br><span class="line">            <span class="comment">//在解析完&lt;Import&gt;元素之后，发送容器导入其他资源处理完成事件</span></span><br><span class="line">            <span class="keyword">this</span>.getReaderContext().fireImportProcessed(location, actResArray, <span class="keyword">this</span>.extractSource(ele));</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"><span class="comment">//解析&lt;Alias&gt;别名元素，为Bean向Spring IoC容器注册别名</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">processAliasRegistration</span><span class="params">(Element ele)</span> </span>&#123;</span><br><span class="line">    <span class="comment">//获取&lt;Alias&gt;别名元素中name的属性值</span></span><br><span class="line">        String name = ele.getAttribute(<span class="string">"name"</span>);</span><br><span class="line">    <span class="comment">//获取&lt;Alias&gt;别名元素中alias的属性值 </span></span><br><span class="line">        String alias = ele.getAttribute(<span class="string">"alias"</span>);</span><br><span class="line">        <span class="keyword">boolean</span> valid = <span class="keyword">true</span>;</span><br><span class="line">    <span class="comment">//&lt;alias&gt;别名元素的name属性值为空</span></span><br><span class="line">        <span class="keyword">if</span> (!StringUtils.hasText(name)) &#123;</span><br><span class="line">            <span class="keyword">this</span>.getReaderContext().error(<span class="string">"Name must not be empty"</span>, ele);</span><br><span class="line">            valid = <span class="keyword">false</span>;</span><br><span class="line">        &#125;</span><br><span class="line">	<span class="comment">//&lt;alias&gt;别名元素的alias属性值为空</span></span><br><span class="line">        <span class="keyword">if</span> (!StringUtils.hasText(alias)) &#123;</span><br><span class="line">            <span class="keyword">this</span>.getReaderContext().error(<span class="string">"Alias must not be empty"</span>, ele);</span><br><span class="line">            valid = <span class="keyword">false</span>;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (valid) &#123;</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                <span class="comment">//向容器的资源读入器注册别名 </span></span><br><span class="line">                <span class="keyword">this</span>.getReaderContext().getRegistry().registerAlias(name, alias);</span><br><span class="line">            &#125; <span class="keyword">catch</span> (Exception var6) &#123;</span><br><span class="line">            <span class="comment">//在解析完&lt;Alias&gt;元素之后，发送容器别名处理完成事件</span></span><br><span class="line">                <span class="keyword">this</span>.getReaderContext().error(<span class="string">"Failed to register alias '"</span> + alias + <span class="string">"' for bean with name '"</span> + name + <span class="string">"'"</span>, ele, var6);</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">this</span>.getReaderContext().fireAliasRegistered(name, alias, <span class="keyword">this</span>.extractSource(ele));</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"><span class="comment">//解析Bean定义资源Document对象的普通元素</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">processBeanDefinition</span><span class="params">(Element ele, BeanDefinitionParserDelegate delegate)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// BeanDefinitionHolder是对BeanDefinition的封装，即Bean定义的封装类,对Document对象中&lt;Bean&gt;元素的解析由BeanDefinitionParserDelegate实现</span></span><br><span class="line">        BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);</span><br><span class="line">        <span class="keyword">if</span> (bdHolder != <span class="keyword">null</span>) &#123;</span><br><span class="line">            bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);</span><br><span class="line"></span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                <span class="comment">//向Spring IoC容器注册解析得到的Bean定义，这是Bean定义向IoC容器注册的入口</span></span><br><span class="line">                BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, <span class="keyword">this</span>.getReaderContext().getRegistry());</span><br><span class="line">            &#125; <span class="keyword">catch</span> (BeanDefinitionStoreException var5) &#123;</span><br><span class="line">                <span class="keyword">this</span>.getReaderContext().error(<span class="string">"Failed to register bean definition with name '"</span> + bdHolder.getBeanName() + <span class="string">"'"</span>, ele, var5);</span><br><span class="line">            &#125;</span><br><span class="line"><span class="comment">//在完成向Spring IoC容器注册解析得到的Bean定义之后，发送注册事件</span></span><br><span class="line">            <span class="keyword">this</span>.getReaderContext().fireComponentRegistered(<span class="keyword">new</span> BeanComponentDefinition(bdHolder));</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<p>通过上述Spring IoC容器对载入的Bean定义Document解析可以看出，我们使用Spring时，在Spring配置文件中可以使用<import>元素来导入IoC容器所需要的其他资源，Spring IoC容器在解析时会首先将指定导入的资源加载进容器中。使用<ailas>别名时，Spring IoC容器首先将别名元素所定义的别名注册到容器中。</ailas></import></p>
<p>对于既不是<import>元素，又不是<alias>元素的元素，即Spring配置文件中普通的<bean>元素的解析由BeanDefinitionParserDelegate类的parseBeanDefinitionElement方法来实现。</bean></alias></import></p>
<h4 id="（12）BeanDefinitionParserDelegate解析Bean定义资源文件中的元素："><a href="#（12）BeanDefinitionParserDelegate解析Bean定义资源文件中的元素：" class="headerlink" title="（12）BeanDefinitionParserDelegate解析Bean定义资源文件中的元素："></a>（12）BeanDefinitionParserDelegate解析Bean定义资源文件中的<bean>元素：</bean></h4><p>Bean定义资源文件中的<import>和<alias>元素解析在DefaultBeanDefinitionDocumentReader中已经完成，对Bean定义资源文件中使用最多的<bean>元素交由BeanDefinitionParserDelegate来解析，其解析实现的源码如下：</bean></alias></import></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//解析&lt;Bean&gt;元素的入口</span></span><br><span class="line"><span class="meta">@Nullable</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> BeanDefinitionHolder <span class="title">parseBeanDefinitionElement</span><span class="params">(Element ele)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">this</span>.parseBeanDefinitionElement(ele, (BeanDefinition)<span class="keyword">null</span>);</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//解析Bean定义资源文件中的&lt;Bean&gt;元素，这个方法中主要处理&lt;Bean&gt;元素的id，name和别名属性 </span></span><br><span class="line"><span class="meta">@Nullable</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> BeanDefinitionHolder <span class="title">parseBeanDefinitionElement</span><span class="params">(Element ele, @Nullable BeanDefinition containingBean)</span> </span>&#123;</span><br><span class="line">    <span class="comment">//获取&lt;Bean&gt;元素中的id属性值</span></span><br><span class="line">    String id = ele.getAttribute(<span class="string">"id"</span>);</span><br><span class="line">    <span class="comment">//获取&lt;Bean&gt;元素中的name属性值</span></span><br><span class="line">    String nameAttr = ele.getAttribute(<span class="string">"name"</span>);</span><br><span class="line">    <span class="comment">//获取&lt;Bean&gt;元素中的alias属性值</span></span><br><span class="line">    List&lt;String&gt; aliases = <span class="keyword">new</span> ArrayList();</span><br><span class="line">    <span class="comment">//将&lt;Bean&gt;元素中的所有name属性值存放到别名中 </span></span><br><span class="line">    <span class="keyword">if</span> (StringUtils.hasLength(nameAttr)) &#123;</span><br><span class="line">        String[] nameArr = StringUtils.tokenizeToStringArray(nameAttr, <span class="string">",; "</span>);</span><br><span class="line">        aliases.addAll(Arrays.asList(nameArr));</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    String beanName = id;</span><br><span class="line">    <span class="comment">//如果&lt;Bean&gt;元素中没有配置id属性时，将别名中的第一个值赋值给beanName</span></span><br><span class="line">    <span class="keyword">if</span> (!StringUtils.hasText(id) &amp;&amp; !aliases.isEmpty()) &#123;</span><br><span class="line">        beanName = (String)aliases.remove(<span class="number">0</span>);</span><br><span class="line">        <span class="keyword">if</span> (<span class="keyword">this</span>.logger.isDebugEnabled()) &#123;</span><br><span class="line">            <span class="keyword">this</span>.logger.debug(<span class="string">"No XML 'id' specified - using '"</span> + beanName + <span class="string">"' as bean name and "</span> + aliases + <span class="string">" as aliases"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">	<span class="comment">//检查&lt;Bean&gt;元素所配置的id或者name的唯一性，containingBean标识&lt;Bean&gt;元素中是否包含子&lt;Bean&gt;元素 </span></span><br><span class="line">    <span class="keyword">if</span> (containingBean == <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="comment">//检查&lt;Bean&gt;元素所配置的id、name或者别名是否重复</span></span><br><span class="line">        <span class="keyword">this</span>.checkNameUniqueness(beanName, aliases, ele);</span><br><span class="line">    &#125;</span><br><span class="line"><span class="comment">//详细对&lt;Bean&gt;元素中配置的Bean定义进行解析的地方</span></span><br><span class="line">    AbstractBeanDefinition beanDefinition = <span class="keyword">this</span>.parseBeanDefinitionElement(ele, beanName, containingBean);</span><br><span class="line">    <span class="keyword">if</span> (beanDefinition != <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="keyword">if</span> (!StringUtils.hasText(beanName)) &#123;</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                <span class="keyword">if</span> (containingBean != <span class="keyword">null</span>) &#123;</span><br><span class="line">              <span class="comment">//如果&lt;Bean&gt;元素中没有配置id、别名或者name，且没有包含子&lt;Bean&gt;元素，为解析的Bean生成一个唯一beanName并注册</span></span><br><span class="line">                    beanName = BeanDefinitionReaderUtils.generateBeanName(beanDefinition, <span class="keyword">this</span>.readerContext.getRegistry(), <span class="keyword">true</span>);</span><br><span class="line">                &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                    <span class="comment">//如果&lt;Bean&gt;元素中没有配置id、别名或者name，且包含了子&lt;Bean&gt;元素，为解析的Bean使用别名向IoC容器注册</span></span><br><span class="line">                    beanName = <span class="keyword">this</span>.readerContext.generateBeanName(beanDefinition);</span><br><span class="line">                    <span class="comment">//为解析的Bean使用别名注册时，为了向后兼容</span></span><br><span class="line">                    String beanClassName = beanDefinition.getBeanClassName();</span><br><span class="line">                    <span class="keyword">if</span> (beanClassName != <span class="keyword">null</span> &amp;&amp; beanName.startsWith(beanClassName) &amp;&amp; beanName.length() &gt; beanClassName.length() &amp;&amp; !<span class="keyword">this</span>.readerContext.getRegistry().isBeanNameInUse(beanClassName)) &#123;</span><br><span class="line">                        aliases.add(beanClassName);</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line"></span><br><span class="line">                <span class="keyword">if</span> (<span class="keyword">this</span>.logger.isDebugEnabled()) &#123;</span><br><span class="line">                    <span class="keyword">this</span>.logger.debug(<span class="string">"Neither XML 'id' nor 'name' specified - using generated bean name ["</span> + beanName + <span class="string">"]"</span>);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125; <span class="keyword">catch</span> (Exception var9) &#123;</span><br><span class="line">                <span class="keyword">this</span>.error(var9.getMessage(), ele);</span><br><span class="line">                <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        String[] aliasesArray = StringUtils.toStringArray(aliases);</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> BeanDefinitionHolder(beanDefinition, beanName, aliasesArray);</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="comment">//当解析出错时，返回null</span></span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//详细对&lt;Bean&gt;元素中配置的Bean定义其他属性进行解析，由于上面的方法中已经对//Bean的id、name和别名等属性进行了处理，该方法中主要处理除这三个以外的其他属性数据 </span></span><br><span class="line"><span class="meta">@Nullable</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> AbstractBeanDefinition <span class="title">parseBeanDefinitionElement</span><span class="params">(Element ele, String beanName, @Nullable BeanDefinition containingBean)</span> </span>&#123;</span><br><span class="line">        <span class="comment">//记录解析的&lt;Bean&gt;</span></span><br><span class="line">        <span class="keyword">this</span>.parseState.push(<span class="keyword">new</span> BeanEntry(beanName));</span><br><span class="line">        <span class="comment">//这里只读取&lt;Bean&gt;元素中配置的class名字，然后载入到BeanDefinition中去只是记录配置的class名字，不做实例化，对象的实例化在依赖注入时完成</span></span><br><span class="line">        String className = <span class="keyword">null</span>;</span><br><span class="line">        <span class="keyword">if</span> (ele.hasAttribute(<span class="string">"class"</span>)) &#123;</span><br><span class="line">            className = ele.getAttribute(<span class="string">"class"</span>).trim();</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        String parent = <span class="keyword">null</span>;</span><br><span class="line">        <span class="keyword">if</span> (ele.hasAttribute(<span class="string">"parent"</span>)) &#123;</span><br><span class="line">            <span class="comment">//如果&lt;Bean&gt;元素中配置了parent属性，则获取parent属性的值</span></span><br><span class="line">            parent = ele.getAttribute(<span class="string">"parent"</span>);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="comment">//根据&lt;Bean&gt;元素配置的class名称和parent属性值创建BeanDefinition为载入Bean定义信息做准备</span></span><br><span class="line">            AbstractBeanDefinition bd = <span class="keyword">this</span>.createBeanDefinition(className, parent);</span><br><span class="line">            <span class="comment">//对当前的&lt;Bean&gt;元素中配置的一些属性进行解析和设置，如配置的单态(singleton)属性等</span></span><br><span class="line">            <span class="keyword">this</span>.parseBeanDefinitionAttributes(ele, beanName, containingBean, bd);</span><br><span class="line">            <span class="comment">//为&lt;Bean&gt;元素解析的Bean设置description信息</span></span><br><span class="line">            bd.setDescription(DomUtils.getChildElementValueByTagName(ele, <span class="string">"description"</span>));</span><br><span class="line">            <span class="comment">//对&lt;Bean&gt;元素的meta(元信息)属性解析</span></span><br><span class="line">            <span class="keyword">this</span>.parseMetaElements(ele, bd);</span><br><span class="line">            <span class="comment">//对&lt;Bean&gt;元素的lookup-method属性解析</span></span><br><span class="line">            <span class="keyword">this</span>.parseLookupOverrideSubElements(ele, bd.getMethodOverrides());</span><br><span class="line">            <span class="comment">//对&lt;Bean&gt;元素的replaced-method属性解析</span></span><br><span class="line">            <span class="keyword">this</span>.parseReplacedMethodSubElements(ele, bd.getMethodOverrides());</span><br><span class="line">            <span class="comment">//解析&lt;Bean&gt;元素的构造方法设置</span></span><br><span class="line">            <span class="keyword">this</span>.parseConstructorArgElements(ele, bd);</span><br><span class="line">            <span class="comment">//解析&lt;Bean&gt;元素的&lt;property&gt;设置</span></span><br><span class="line">            <span class="keyword">this</span>.parsePropertyElements(ele, bd);</span><br><span class="line">            <span class="comment">//解析&lt;Bean&gt;元素的qualifier属性</span></span><br><span class="line">            <span class="keyword">this</span>.parseQualifierElements(ele, bd);</span><br><span class="line">            <span class="comment">//为当前解析的Bean设置所需的资源和依赖对象</span></span><br><span class="line">            bd.setResource(<span class="keyword">this</span>.readerContext.getResource());</span><br><span class="line">            bd.setSource(<span class="keyword">this</span>.extractSource(ele));</span><br><span class="line">            AbstractBeanDefinition var7 = bd;</span><br><span class="line">            <span class="keyword">return</span> var7;</span><br><span class="line">        &#125; <span class="keyword">catch</span> (ClassNotFoundException var13) &#123;</span><br><span class="line">            <span class="keyword">this</span>.error(<span class="string">"Bean class ["</span> + className + <span class="string">"] not found"</span>, ele, var13);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (NoClassDefFoundError var14) &#123;</span><br><span class="line">            <span class="keyword">this</span>.error(<span class="string">"Class that bean class ["</span> + className + <span class="string">"] depends on not found"</span>, ele, var14);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Throwable var15) &#123;</span><br><span class="line">            <span class="keyword">this</span>.error(<span class="string">"Unexpected failure during bean definition parsing"</span>, ele, var15);</span><br><span class="line">        &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">            <span class="keyword">this</span>.parseState.pop();</span><br><span class="line">        &#125;</span><br><span class="line">	<span class="comment">//解析&lt;Bean&gt;元素出错时，返回null</span></span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<p>只要使用过Spring，对Spring配置文件比较熟悉的人，通过对上述源码的分析，就会明白我们在Spring配置文件中<bean>元素的中配置的属性就是通过该方法解析和设置到Bean中去的。</bean></p>
<p>注意：在解析<bean>元素过程中没有创建和实例化Bean对象，只是创建了Bean对象的定义类BeanDefinition，将<bean>元素中的配置信息设置到BeanDefinition中作为记录，当依赖注入时才使用这些记录信息创建和实例化具体的Bean对象。</bean></bean></p>
<p>上面方法中一些对一些配置如元信息(meta)、qualifier等的解析，我们在Spring中配置时使用的也不多，我们在使用Spring的<bean>元素时，配置最多的是<property>属性，因此我们下面继续分析源码，了解Bean的属性在解析时是如何设置的。</property></bean></p>
<h4 id="（13）BeanDefinitionParserDelegate解析元素："><a href="#（13）BeanDefinitionParserDelegate解析元素：" class="headerlink" title="（13）BeanDefinitionParserDelegate解析元素："></a>（13）BeanDefinitionParserDelegate解析<property>元素：</property></h4><p>BeanDefinitionParserDelegate在解析<bean>调用parsePropertyElements方法解析<bean>元素中的<property>属性子元素，解析源码如下：</property></bean></bean></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//解析&lt;Bean&gt;元素中的&lt;property&gt;子元素</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">parsePropertyElements</span><span class="params">(Element beanEle, BeanDefinition bd)</span> </span>&#123;</span><br><span class="line">    <span class="comment">//获取&lt;Bean&gt;元素中所有的子元素</span></span><br><span class="line">    NodeList nl = beanEle.getChildNodes();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span>(<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; nl.getLength(); ++i) &#123;</span><br><span class="line">        Node node = nl.item(i);</span><br><span class="line">        <span class="comment">//如果子元素是&lt;property&gt;子元素，则调用解析&lt;property&gt;子元素方法解析</span></span><br><span class="line">        <span class="keyword">if</span> (<span class="keyword">this</span>.isCandidateElement(node) &amp;&amp; <span class="keyword">this</span>.nodeNameEquals(node, <span class="string">"property"</span>)) &#123;</span><br><span class="line">            <span class="keyword">this</span>.parsePropertyElement((Element)node, bd);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//解析&lt;property&gt;元素 </span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">parsePropertyElement</span><span class="params">(Element ele, BeanDefinition bd)</span> </span>&#123;</span><br><span class="line">    <span class="comment">//获取&lt;property&gt;元素的名字</span></span><br><span class="line">        String propertyName = ele.getAttribute(<span class="string">"name"</span>);</span><br><span class="line">        <span class="keyword">if</span> (!StringUtils.hasLength(propertyName)) &#123;</span><br><span class="line">            <span class="keyword">this</span>.error(<span class="string">"Tag 'property' must have a 'name' attribute"</span>, ele);</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="keyword">this</span>.parseState.push(<span class="keyword">new</span> PropertyEntry(propertyName));</span><br><span class="line"></span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                <span class="comment">//如果一个Bean中已经有同名的property存在，则不进行解析，直接返回。即如果在同一个Bean中配置同名的property，则只有第一个起作用</span></span><br><span class="line">                <span class="keyword">if</span> (!bd.getPropertyValues().contains(propertyName)) &#123;</span><br><span class="line">                    Object val = <span class="keyword">this</span>.parsePropertyValue(ele, bd, propertyName);</span><br><span class="line">                    PropertyValue pv = <span class="keyword">new</span> PropertyValue(propertyName, val);</span><br><span class="line">                    <span class="keyword">this</span>.parseMetaElements(ele, pv);</span><br><span class="line">                    pv.setSource(<span class="keyword">this</span>.extractSource(ele));</span><br><span class="line">                    bd.getPropertyValues().addPropertyValue(pv);</span><br><span class="line">                    <span class="keyword">return</span>;</span><br><span class="line">                &#125;</span><br><span class="line"></span><br><span class="line">                <span class="keyword">this</span>.error(<span class="string">"Multiple 'property' definitions for property '"</span> + propertyName + <span class="string">"'"</span>, ele);</span><br><span class="line">            &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">                <span class="keyword">this</span>.parseState.pop();</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
      
    </div>

    

    
    
    

    
        
<div class="my_post_copyright">
  <script src="//cdn.bootcss.com/clipboard.js/1.5.10/clipboard.min.js"></script>
  
  <!-- JS库 sweetalert 可修改路径 -->
  <script type="text/javascript" src="http://jslibs.wuxubj.cn/sweetalert_mini/jquery-1.7.1.min.js"></script>
  <script src="http://jslibs.wuxubj.cn/sweetalert_mini/sweetalert.min.js"></script>
  <link rel="stylesheet" type="text/css" href="http://jslibs.wuxubj.cn/sweetalert_mini/sweetalert.mini.css">
 
  <p><span>本文标题:</span>Spring IOC源码解析</p>
  <p><span>文章作者:</span>xieyuanhui</p>
  <p><span>发布时间:</span>2019年06月28日 - 11:29:43</p>
  <p><span>最后更新:</span>2019年07月08日 - 17:14:30</p>
  <p><span>原始链接:</span><a href="/xieyuanhui/2019/06/28/Spring-IOC源码解析/" title="Spring IOC源码解析">http://xyh5513.gitee.io/xieyuanhui/2019/06/28/Spring-IOC源码解析/</a>
    <span class="copy-path" title="点击复制文章链接"><i class="fa fa-clipboard" data-clipboard-text="http://xyh5513.gitee.io/xieyuanhui/2019/06/28/Spring-IOC源码解析/" aria-label="复制成功！"></i></span>
  </p>
  <p><span>许可协议:</span><i class="fa fa-creative-commons"></i> <a rel="license" href="https://creativecommons.org/licenses/by-nc-nd/4.0/" target="_blank" title="Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0)">CC BY-NC-SA 4.0</a> 转载请保留原文链接及作者。</p>  
</div>
<script> 
    var clipboard = new Clipboard('.fa-clipboard');
    clipboard.on('success', $(function(){
      $(".fa-clipboard").click(function(){
        swal({   
          title: "",   
          text: '复制成功',   
          html: false,
          timer: 500,   
          showConfirmButton: false
        });
      });
    }));  
</script>

    

    

    
      
    
    
      <div>
        <div id="reward-container">
  <div>您的支持将鼓励我继续创作</div>
  <button id="reward-button" disable="enable" onclick="var qr = document.getElementById(&quot;qr&quot;); qr.style.display = (qr.style.display === 'none') ? 'block' : 'none';">
    打赏
  </button>
  <div id="qr" style="display: none;">

    
      
      
        
      
      <div style="display: inline-block">
        <img src="/xieyuanhui/images/wechatpay.png" alt="xieyuanhui 微信支付">
        <p>微信支付</p>
      </div>
    
      
      
        
      
      <div style="display: inline-block">
        <img src="/xieyuanhui/images/alipay.jpg" alt="xieyuanhui 支付宝">
        <p>支付宝</p>
      </div>
    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/xieyuanhui/tags/Spring/" rel="tag"># Spring</a>
          
            <a href="/xieyuanhui/tags/IOC/" rel="tag"># IOC</a>
          
        </div>
      

      
      
        <div class="post-widgets">
        

        

        
          
          <div class="social_share">
            
            
              <div id="needsharebutton-postbottom">
                <span class="btn">
                  <i class="fa fa-share-alt" aria-hidden="true"></i>
                </span>
              </div>
            
            
          </div>
        
        </div>
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/xieyuanhui/2019/06/27/Redis更新缓存问题/" rel="next" title="Redis更新缓存问题">
                <i class="fa fa-chevron-left"></i> Redis更新缓存问题
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/xieyuanhui/2019/07/01/Redis面试题/" rel="prev" title="Redis面试题">
                Redis面试题 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>


  </div>


          </div>
          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/xieyuanhui/images/deer.png" alt="xieyuanhui">
            
              <p class="site-author-name" itemprop="name">xieyuanhui</p>
              <div class="site-description motion-element" itemprop="description"></div>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/xieyuanhui/archives/">
                
                    <span class="site-state-item-count">107</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  
                    
                      <a href="/xieyuanhui/categories/">
                    
                  
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">16</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  
                    
                      <a href="/xieyuanhui/tags/">
                    
                  
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">114</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          
            <div class="feed-link motion-element">
              <a href="/xieyuanhui/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="/xieyuanhui/yuanhxie@163.com" title="E-Mail &rarr; yuanhxie@163.com"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                </span>
              
            </div>
          

          

          
          

          
            
          
          

        </div>
      </div>

      
      <!--noindex-->
        <div class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
            
            
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#一、什么是Ioc-DI？"><span class="nav-text">一、什么是Ioc/DI？</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#二、-Spring-IOC体系结构？"><span class="nav-text">二、 Spring IOC体系结构？</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-BeanFactory"><span class="nav-text">(1) BeanFactory</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-BeanDefinition"><span class="nav-text">(2) BeanDefinition</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#三、IoC容器的初始化？"><span class="nav-text">三、IoC容器的初始化？</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1、XmlBeanFactory-屌丝IOC-的整个流程"><span class="nav-text">1、XmlBeanFactory(屌丝IOC)的整个流程</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2、FileSystemXmlApplicationContext-的IOC容器流程"><span class="nav-text">2、FileSystemXmlApplicationContext 的IOC容器流程</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1-高富帅IOC解剖"><span class="nav-text">(1) 高富帅IOC解剖</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-设置资源加载器和资源定位"><span class="nav-text">(2) 设置资源加载器和资源定位</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#（3）AbstractApplicationContext的refresh函数载入Bean定义过程："><span class="nav-text">（3）AbstractApplicationContext的refresh函数载入Bean定义过程：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#（4）AbstractApplicationContext子类的refreshBeanFactory-方法："><span class="nav-text">（4）AbstractApplicationContext子类的refreshBeanFactory()方法：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#（5）AbstractRefreshableApplicationContext子类的loadBeanDefinitions方法："><span class="nav-text">（5）AbstractRefreshableApplicationContext子类的loadBeanDefinitions方法：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#（6）AbstractBeanDefinitionReader读取Bean定义资源："><span class="nav-text">（6）AbstractBeanDefinitionReader读取Bean定义资源：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#（7）资源加载器获取要读入的资源："><span class="nav-text">（7）资源加载器获取要读入的资源：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#（8）XmlBeanDefinitionReader加载Bean定义资源："><span class="nav-text">（8）XmlBeanDefinitionReader加载Bean定义资源：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#（9）DocumentLoader将Bean定义资源转换为Document对象："><span class="nav-text">（9）DocumentLoader将Bean定义资源转换为Document对象：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#（10）XmlBeanDefinitionReader解析载入的Bean定义资源文件："><span class="nav-text">（10）XmlBeanDefinitionReader解析载入的Bean定义资源文件：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#（11）DefaultBeanDefinitionDocumentReader对Bean定义的Document对象解析："><span class="nav-text">（11）DefaultBeanDefinitionDocumentReader对Bean定义的Document对象解析：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#（12）BeanDefinitionParserDelegate解析Bean定义资源文件中的元素："><span class="nav-text">（12）BeanDefinitionParserDelegate解析Bean定义资源文件中的元素：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#（13）BeanDefinitionParserDelegate解析元素："><span class="nav-text">（13）BeanDefinitionParserDelegate解析元素：</span></a></li></ol></li></ol></li></ol></div>
            

          </div>
        </div>
      <!--/noindex-->
      

      

    </div>
  </aside>
  


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">xieyuanhui</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">站点总字数：</span>
    
    <span title="站点总字数">749k</span>
  

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
    
      <span class="post-meta-item-text">站点阅读时长 &asymp;</span>
    
    <span title="站点阅读时长">11:21</span>
  
</div>


  <div class="powered-by">由 <a href="https://hexo.io" class="theme-link" rel="noopener" target="_blank">Hexo</a> 强力驱动 v3.8.0</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 – <a href="https://theme-next.org" class="theme-link" rel="noopener" target="_blank">NexT.Pisces</a> v7.1.0</div>


<div><span id="sitetime"></span>
<script language="javascript">
  function siteTime(){
    window.setTimeout("siteTime()", 1000);
    var seconds = 1000;
    var minutes = seconds * 60;
    var hours = minutes * 60;
    var days = hours * 24;
    var years = days * 365;
    var today = new Date();
    var todayYear = today.getFullYear();
    var todayMonth = today.getMonth()+1;
    var todayDate = today.getDate();
    var todayHour = today.getHours();
    var todayMinute = today.getMinutes();
    var todaySecond = today.getSeconds();
    /* Date.UTC() -- 返回date对象距世界标准时间(UTC)1970年1月1日午夜之间的毫秒数(时间戳)
    year - 作为date对象的年份，为4位年份值
    month - 0-11之间的整数，做为date对象的月份
    day - 1-31之间的整数，做为date对象的天数
    hours - 0(午夜24点)-23之间的整数，做为date对象的小时数
    minutes - 0-59之间的整数，做为date对象的分钟数
    seconds - 0-59之间的整数，做为date对象的秒数
    microseconds - 0-999之间的整数，做为date对象的毫秒数 */
    var t1 = Date.UTC(2019,04,09,15,00,00); //北京时间2018-2-13 00:00:00
    var t2 = Date.UTC(todayYear,todayMonth,todayDate,todayHour,todayMinute,todaySecond);
    var diff = t2-t1;
    var diffYears = Math.floor(diff/years);
    var diffDays = Math.floor((diff/days)-diffYears*365);
    var diffHours = Math.floor((diff-(diffYears*365+diffDays)*days)/hours);
    var diffMinutes = Math.floor((diff-(diffYears*365+diffDays)*days-diffHours*hours)/minutes);
    var diffSeconds = Math.floor((diff-(diffYears*365+diffDays)*days-diffHours*hours-diffMinutes*minutes)/seconds);
    document.getElementById("sitetime").innerHTML=" xieyuanhui的个人笔记已运行"+/*diffYears+" 年 "+*/diffDays+" 天 "+diffHours+" 小时 "+diffMinutes+" 分钟 "+diffSeconds+" 秒";
  }/*因为建站时间还没有一年，就将之注释掉了。需要的可以取消*/
  siteTime();
</script></div>



<div>

  <div class="theme-info">
    <script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span id="busuanzi_container_site_pv">本站总访问量<span id="busuanzi_value_site_pv"></span>次</span>
    <span class="post-meta-divider">|</span>
    <span id="busuanzi_container_site_uv">本站访客数<span id="busuanzi_value_site_uv"></span>人</span>
  </div>

</div>

        






  <div>
    <script type="text/javascript">
	    var cnzz_protocol = (("https:" == document.location.protocol) ? "https://" : "http://");
	    document.write(unescape("%3Cspan id='cnzz_stat_icon_1277235632'%3E%3C/span%3E%3Cscript 
	    src='" + cnzz_protocol + "s23.cnzz.com/z_stat.php%3Fid%3D1277235632%26show%3Dpic' 
	    type='text/javascript'%3E%3C/script%3E"));
    </script>
  </div>



        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    
      <div id="needsharebutton-float">
        <span class="btn">
          <i class="fa fa-share-alt" aria-hidden="true"></i>
        </span>
      </div>
    

    

    
  </div>

  

<script>
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>












  



  
    
    
  
  <script color="0,0,255" opacity="0.5" zindex="-1" count="99" src="/xieyuanhui/lib/canvas-nest/canvas-nest.min.js"></script>













  
  <script src="/xieyuanhui/lib/jquery/index.js?v=2.1.3"></script>

  
  <script src="/xieyuanhui/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script src="/xieyuanhui/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script src="/xieyuanhui/lib/fancybox/source/jquery.fancybox.pack.js"></script>


  


  <script src="/xieyuanhui/js/utils.js?v=7.1.0"></script>

  <script src="/xieyuanhui/js/motion.js?v=7.1.0"></script>



  
  


  <script src="/xieyuanhui/js/affix.js?v=7.1.0"></script>

  <script src="/xieyuanhui/js/schemes/pisces.js?v=7.1.0"></script>



  
  <script src="/xieyuanhui/js/scrollspy.js?v=7.1.0"></script>
<script src="/xieyuanhui/js/post-details.js?v=7.1.0"></script>



  


  <script src="/xieyuanhui/js/next-boot.js?v=7.1.0"></script>


  

  

  

  


  


  
  <script>
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/xieyuanhui/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url).replace(/\/{2,}/g, '/');
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x"></i></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x"></i></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  
  
  <script>
    
    function addCount(Counter) {
      var $visitors = $('.leancloud_visitors');
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();

      Counter('get', '/classes/Counter', { where: JSON.stringify({ url }) })
        .done(function({ results }) {
          if (results.length > 0) {
            var counter = results[0];
            
            Counter('put', '/classes/Counter/' + counter.objectId, JSON.stringify({ time: { '__op': 'Increment', 'amount': 1 } }))
            
              .done(function() {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.time + 1);
              })
            
              .fail(function ({ responseJSON }) {
                console.log('Failed to save Visitor num, with error message: ' + responseJSON.error);
              })
          } else {
            
              Counter('post', '/classes/Counter', JSON.stringify({ title: title, url: url, time: 1 }))
                .done(function() {
                  var $element = $(document.getElementById(url));
                  $element.find('.leancloud-visitors-count').text(1);
                })
                .fail(function() {
                  console.log('Failed to create');
                });
            
          }
        })
        .fail(function ({ responseJSON }) {
          console.log('LeanCloud Counter Error: ' + responseJSON.code + ' ' + responseJSON.error);
        });
    }
    

    $(function() {
      $.get('https://app-router.leancloud.cn/2/route?appId=' + 'q2BU0OM2W8i5nARddHRKQOvm-gzGzoHsz')
        .done(function({ api_server }) {
          var Counter = function(method, url, data) {
            return $.ajax({
              method: method,
              url: 'https://' + api_server + '/1.1' + url,
              headers: {
                'X-LC-Id': 'q2BU0OM2W8i5nARddHRKQOvm-gzGzoHsz',
                'X-LC-Key': 'hLTPk12Jmt8atnC9cePjTwQH',
                'Content-Type': 'application/json',
              },
              data: data
            });
          };
          
            addCount(Counter);
          
        });
    });
  </script>



  

  
  

  
  

  
    
      <script type="text/x-mathjax-config">
  

  MathJax.Hub.Config({
    tex2jax: {
      inlineMath: [ ['$', '$'], ['\\(', '\\)'] ],
      processEscapes: true,
      skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
    },
    TeX: {
      
      equationNumbers: {
        autoNumber: 'AMS'
      }
    }
  });
  MathJax.Hub.Register.StartupHook('TeX Jax Ready', function() {
    MathJax.InputJax.TeX.prefilterHooks.Add(function(data) {
      if (data.display) {
        var next = data.script.nextSibling;
        while (next && next.nodeName.toLowerCase() === '#text') { next = next.nextSibling }
        if (next && next.nodeName.toLowerCase() === 'br') { next.parentNode.removeChild(next) }
      }
    });
  });
</script>

<script type="text/x-mathjax-config">
  MathJax.Hub.Queue(function() {
    var all = MathJax.Hub.getAllJax(), i;
    for (i = 0; i < all.length; i += 1) {
      document.getElementById(all[i].inputID + '-Frame').parentNode.className += ' has-jax';
    }
  });
</script>
<script src="//cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-MML-AM_CHTML"></script>

    
  


  

  

  

  

  
  
  
  <script src="/xieyuanhui/lib/needsharebutton/needsharebutton.js"></script>
  <script>
    
      pbOptions = {};
      
        pbOptions.iconStyle = "box";
      
        pbOptions.boxForm = "horizontal";
      
        pbOptions.position = "bottomCenter";
      
        pbOptions.networks = "Weibo,Wechat,Douban,QQZone,Twitter,Facebook";
      
      new needShareButton('#needsharebutton-postbottom', pbOptions);
    
    
      flOptions = {};
      
        flOptions.iconStyle = "box";
      
        flOptions.boxForm = "horizontal";
      
        flOptions.position = "middleRight";
      
        flOptions.networks = "Weibo,Wechat,Douban,QQZone,Twitter,Facebook";
      
      new needShareButton('#needsharebutton-float', flOptions);
    
  </script>


  

  

  

  

  

  


  
  <script type="text/javascript" src="//cdn.bootcss.com/canvas-nest.js/1.0.0/canvas-nest.min.js"></script><!-- hexo-inject:begin --><!-- Begin: Injected MathJax -->
<script type="text/x-mathjax-config">
  MathJax.Hub.Config({"tex2jax":{"inlineMath":[["$","$"],["\\(","\\)"]],"skipTags":["script","noscript","style","textarea","pre","code"],"processEscapes":true},"TeX":{"equationNumbers":{"autoNumber":"AMS"}}});
</script>

<script type="text/x-mathjax-config">
  MathJax.Hub.Queue(function() {
    var all = MathJax.Hub.getAllJax(), i;
    for(i=0; i < all.length; i += 1) {
      all[i].SourceElement().parentNode.className += ' has-jax';
    }
  });
</script>

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js">
</script>
<!-- End: Injected MathJax -->
<!-- hexo-inject:end -->
  
</body>
</html>
